Skip to content

Commit 8c4de20

Browse files
authored
cgen, json: make errors more informative (resolve empty panics) (related: #21184) (#22898)
1 parent 73786b8 commit 8c4de20

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

vlib/json/tests/json_decode_test.v

+4-4
Original file line numberDiff line numberDiff line change
@@ -90,15 +90,15 @@ struct DbConfig {
9090

9191
fn test_decode_error_message_should_have_enough_context_empty() {
9292
json.decode(DbConfig, '') or {
93-
assert err.msg().len < 2
93+
assert err.msg() == 'failed to decode JSON string'
9494
return
9595
}
9696
assert false
9797
}
9898

9999
fn test_decode_error_message_should_have_enough_context_just_brace() {
100100
json.decode(DbConfig, '{') or {
101-
assert err.msg() == '{'
101+
assert err.msg() == 'failed to decode JSON string: {'
102102
return
103103
}
104104
assert false
@@ -111,7 +111,7 @@ fn test_decode_error_message_should_have_enough_context_trailing_comma_at_end()
111111
"user": "alex",
112112
}'
113113
json.decode(DbConfig, txt) or {
114-
assert err.msg() == ' "user": "alex",\n}'
114+
assert err.msg().contains(' "user": "alex",\n}')
115115
return
116116
}
117117
assert false
@@ -120,7 +120,7 @@ fn test_decode_error_message_should_have_enough_context_trailing_comma_at_end()
120120
fn test_decode_error_message_should_have_enough_context_in_the_middle() {
121121
txt := '{"host": "localhost", "dbname": "alex" "user": "alex", "port": "1234"}'
122122
json.decode(DbConfig, txt) or {
123-
assert err.msg() == 'ost", "dbname": "alex" "user":'
123+
assert err.msg().contains('ost", "dbname": "alex" "user":')
124124
return
125125
}
126126
assert false

vlib/v/gen/c/json.v

+8-3
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,11 @@ ${dec_fn_dec} {
9595
${init_styp};
9696
if (!root) {
9797
const char *error_ptr = cJSON_GetErrorPtr();
98-
if (error_ptr != NULL) {
98+
if (error_ptr != NULL) {
9999
const int error_pos = (int)cJSON_GetErrorPos();
100100
int maxcontext_chars = 30;
101101
byte *buf = vcalloc_noscan(maxcontext_chars + 10);
102-
if(error_pos > 0) {
102+
if (error_pos > 0) {
103103
int backlines = 1;
104104
int backchars = error_pos < maxcontext_chars-7 ? (int)error_pos : maxcontext_chars-7 ;
105105
char *prevline_ptr = (char*)error_ptr;
@@ -119,7 +119,12 @@ ${dec_fn_dec} {
119119
int maxchars = vstrlen_char(prevline_ptr);
120120
vmemcpy(buf, prevline_ptr, (maxchars < maxcontext_chars ? maxchars : maxcontext_chars));
121121
}
122-
return (${result_name}_${ret_styp}){.is_error = true,.err = _v_error(tos2(buf)),.data = {0}};
122+
string msg;
123+
msg = _SLIT("failed to decode JSON string");
124+
if (buf[0] != \'\\0\') {
125+
msg = string__plus(msg, _SLIT(": "));
126+
}
127+
return (${result_name}_${ret_styp}){.is_error = true,.err = _v_error(string__plus(msg, tos2(buf))),.data = {0}};
123128
}
124129
}
125130
')

0 commit comments

Comments
 (0)