c# - Is error that specified in JsonSerializerSettings catches all exceptions -


i try implement code error handling newtonsoft documentation

i using following jsonserializersettings

errors = new jsonerrors(); jsonserializersettings = new jsonserializersettings {     error = delegate (object sender, erroreventargs args)     {         errors.add(args.errorcontext.error.message);         args.errorcontext.handled = true;     }  }; 

i use following code deserialize response.

try {     deserializedobject = jsonconvert.deserializeobject(response, jsonserializersettings); } catch (exception ex) {     console.writeline(ex.message);     throw; } 

if add chars @ end of response string expect catch deserialize exception see relevant error added jsonerrors object.

can sure error raised de-serialization/serialization catched jsonserializersettings mechanism. can remove try catch in code?

in theory exceptions should caught , passed handler (other exceptions cannot caught such stackoverflowexception.) if go github source , search iserrorhandled see types of exception caught, instance here:

        catch (exception ex)         {             if (iserrorhandled(null, contract, null, reader ijsonlineinfo, reader.path, ex))             {                 handleerror(reader, false, 0);                 return null;             }             else             {                 // clear context in case serializer being used inside converter                 // if converter wraps error not clearing context cause error:                 // "current error context error different requested error."                 clearerrorcontext();                 throw;             }         } 

that being said, in practice there may edge cases not work. instance, in previous answer noted exceptions thrown onserializing event of root object cannot handled -- though seems not reproducible in current version (9.0) of json.net. in current version, if exception thrown trying create contract root object, json.net not catch , handle it. happen because of buggy custom contract resolver, or because of mistake in applying serialization attributes root object. instance, trying serialize or deserialize following root object:

public class badextensiondata {     dictionary<string, object> extensiondata;      [jsonextensiondata]     public dictionary<string, object> extensiondata { set { extensiondata = value; } } } 

will result in unhandled exception:

newtonsoft.json.jsonexception: invalid extension data attribute on 'badextensiondata'. member 'extensiondata' must have getter. 

thus may want leave outer try/catch in case (and report issue exceptions cannot handled).

finally, aware catching , swallowing exceptions considered bad practice.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -