cJSON icon indicating copy to clipboard operation
cJSON copied to clipboard

Completion of error handling

Open elfring opened this issue 6 years ago • 7 comments

Would you like to add more error handling for return values from a function like “cJSON_strdup”?

elfring avatar Apr 28 '19 19:04 elfring

Yeah, it might make sense to catch a NULL from cJSON_strdup, although this sadly won't enable any error handling from the external API since these are void functions.

FSMaxB avatar Apr 30 '19 17:04 FSMaxB

How do you think about to adjust the return type for affected functions?

elfring avatar Apr 30 '19 17:04 elfring

I have add some code to retrieve line number when error occur, whether syntax error in JSON or name/value is invalid for us.

demo1:

$cat -n demo2.json 
    1  {
    2      "name": "Awesome 4K",
    3      "resolutions": [
    4          {
    5              "width": 1280;  # ';' should be ','
    6              "height": 720
    7          },

$./parser2 demo2.json 
parse error: line: 5, content: ;
            "height": 720

demo2:

$cat -n demo4.json 
     1  {
     2      "name": "Awesome 4K",
     3      "resolutions": [
     4          {
     5              "width": "what?", # width's value should be integer
     6              "height": 720
     7          },
     
$./parser2 ./demo4.json 
"name": "Awesome 4K"
resolutions:
invalid "width" value: object: width, line: 5
  • my cJSON fork: https://github.com/zzqcn/cJSON/tree/error-line
  • sample: https://github.com/zzqcn/storage/tree/master/code/c/cjson
  • doc(Chinese): https://www.yuque.com/zzqcn/ftvl2p/wu0kb5

zzqcn avatar Oct 22 '19 08:10 zzqcn

Error handling makes sense, I like the demo1, when the input string is an invalid json string, the parse function should tell us where the problem is.

But I can't agree with demo2, we can't judge whether a field is string or number based on the field name. The value of "width" could be "100mm" while the "height"'s value is "2m" in some specific scenarios.

Alanscut avatar Oct 22 '19 11:10 Alanscut

Hi @zzqcn , will you submit a PR?

Alanscut avatar Nov 05 '19 06:11 Alanscut

@Alanscut I'm not sure it's userful to everyone, maybe you can review my code and make a desision.

zzqcn avatar Nov 05 '19 06:11 zzqcn

@zzqcn I think your getErrorMsg function is a great addition. The only issue I have with cJSON at the moment is the lack of helpful error message when there is a syntax error in the file. A simple line number and a print of the line in which the error occurred is perfect! Please send in a Pull Request as @Alanscut said, I'd like to make use of this.

Also as @Alanscut points out, the functionality in your demo1 is useful since a json file is either syntactically correct or not, but the functionality in demo2 should not be included. That's up to the end user to decide what particular type an entry should be and handle it for their own use case.

StrawsonDesign avatar Sep 08 '20 05:09 StrawsonDesign