You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Get a catch block error message with TypeScript: give a more "universal" solution #206
Hi Kent, I went through your article about error handling, because we just faced the exact same issue :)
But we figured out that the proposed solution might not fit all cases, since many framework are throwing errors that comply to the Error api, but aren't instance of Error.
Then I would propose the following implementation as a more "universal" way of handling errors:
typeErrorWithMessage={message: string;}functionisErrorWithMessage(error: unknown): error is ErrorWithMessage{returntypeoferror==='object'&&'message'inerror;}functiongetErrorMessage(error: unknown){if(isErrorWithMessage(error))returnerror.messagereturnString(error)}
This should allow program to cope with any errors thrown by all frameworks (apollo, axios, etc…)
Activity
kentcdodds commentedon Oct 29, 2021
Thanks! I've added this to the post :)
jpeyper commentedon Nov 3, 2021
My typescript may not be the best, but the type guard doesn't guarantee that the message field on the error is a string, does it?
kentcdodds commentedon Nov 3, 2021
Hi @jpeyper! You're right. I've updated the blog post to account for that. Thanks!