Error handling in TypedJSON<T>.parse
Closed this issue · 2 comments
As it stands now, TypedJSON.parse seems to be able to return T | undefined
, but also throw if it has an user-defined error handler that throws. In my opinion, it'd be better to always just return T
and throw on errors, or at least give an alternative like that (parseOrErr kinda method for example).
Because most of my cope relies on throwing if errors occur, having to create wrappers for the undefined
behavior (or type assertions and always defining custom error handlers) is a pain.
Hopefully this will spark some discussion, so I'll know if I should create my own fork or not :)
Hey @Ijoonal, this may not be the most correct solution, but admittedly you can just define your error handler to log to console/sentry/etc or provide a default and do a short if statement to handle an undefined instead of using the verbose try/catch.
To ease your pain, I can recommend you to set a global error handler like this:
TypedJSON.setGlobalConfig({
errorHandler: (e => {throw e;}),
});
And assert a type with a !
, like this:
const obj = TypedJSON.parse(json, Clazz)!;
Then, apart from the extra 3 initialisation lines, it is only a single character for you to write which seems slightly less than maintaining a fork :)
I still find it questionable to use both undefined and throws for error handling, but I guess that that's an okay-ish way to handle it too, thanks :)