Premprakash Singh
Student undergrad & developer, Learner, on the road to become fullstack developer
I have a Project created using Node.js and it does not have any error logging in it at the moment. Does anyone know what are some best practices to add error logging in an existing Node.js project?
If you have any good resources please share. Any help will be appreciated.
Make sure your catch handlers (promises or try...catch) have a log statement.
Pass the whole error object as a parameter to your log function - this will make sure you get the stack trace (don't convert it to a string).
Ensure you are printing enough context at the start of a (potentially error prone) flow so you can trace the error back to the event that started it. Also consider printing that contextual information with the log statement.
Use console.error (or your logging framework equivalent) so it's separate and obvious.
Udayaditya Singh
There are three basic patterns for a function to deliver errors.
Throw delivers an error synchronously — that is, in the same context where the function was called. If the caller used try/catch, then they can catch the error. If none of the callers did, the program usually crashes.
Callbacks are the most basic way of delivering an error asynchronously. The user passes you a function (the callback), and you invoke it sometime later when the asynchronous operation completes. The usual pattern is that the callback is invoked as callback(err, result), where only one of err and result is non-null, depending on whether the operation succeeded or failed.
Promise rejections are a common way to deliver an error asynchrously. This method is growing in popularity since the release of Node.js version 8 that includes support for async/await. This allows asynchrounous code to be written to look like synchronous code and to catch errors using try/catch.
3.For more complicated cases, instead of using a callback, the function itself can return an EventEmitter object, and the caller would be expected to listen for error events on the emitter.
Please have a Look into this article : joyent.com/node-js/production/design/errors
Thank You.