When writing node applications I often need both stack traces and context to quickly resolve issues. Context here would be something like process information, variable state, queue job identifier, or (if a web server) a HTTP client header.My best solution so far has been to wrap all errors in a context object and then test for that object in the final error logging/handling block.... try { return fooFails(); } catch (err) { return errorWithContext(err, {bar: 1234}); } orfooFails() .then(() => ({ok: true})) .catch(err => errorWithContext(err, {bar: 1234})); Then in my logger I can type check to handle displaying both the stack and context of the error.function log(err) { if(err instanceof ErrorWithContext) { ... } else if (err instanceof Error) { ... } else { ... } } Is this the right/best way to handle errors? I currently use winston & morgan for actual logging/console display of the final error messages.
Submitted July 10, 2018 at 05:55PM by Xeoncross
No comments:
Post a Comment