Conventionally, an error condition in a Node program is a non-fatal condition that should be caught and handled, seen most explicitly in the Error as first argument convention displayed by the typical Node callback pattern. An exception is a serious error (a system error) that a sane environment should not ignore or try to handle.
One comes across four common error contexts in Node, and should respond predictably:
- A synchronous context: This will normally happen in the context of a function, where a bad call signature or another non-fatal error is detected. The function should simply return an error object;
new Error(...)
, or some other consistent indicator that the function call has failed. - An asynchronous context: When expected to respond by firing a callback function, the execution context should pass an Error object, with appropriate message, as the first argument to that callback .
- An event context: Quoting the Node documentation: "When an EventEmitter instance experiences an error, the typical action is to emit an error event. Error events are treated as a special case in node. If there is no listener for it, then the default action is to print a stack trace and exit the program." Use events where events are expected.
- A Promise context: A Promise throws or is otherwise rejected, and this error is caught within a .catch block. Important note: you should always reject Promises with true Error objects. Petka Antonov, author of the popular Bluebird Promises implementation, discusses why:
https://github.com/petkaantonov/bluebird/blob/master/docs/docs/warning-explanations.md