Error event listeners can be defined with app.on('error'). They are particularly useful for centralized logging and error reporting. The error listeners receive all errors that are thrown in the middleware chain, except the ones that are caught and are neither rethrown or emitted using app.emit(). To define an error handler, refer to this code:
app.on('error', err => {
// log errors
console.error("server error", err);
});
If no event listener is defined, then app.onerror is used. This simply outputs the error to stdout unless app.silent is true, err.status is 404, or err.expose is set to true.
If an error is thrown in the middleware chain and it is not possible to respond to the client, the context object is also passed to the event listener:
app.on('error', (err, ctx) => {
console.error("server error", err, ctx);
});
It is important to note that these are user-level errors and are therefore safe to expose to the user (err.expose is set to true). This is usually not the case for all error messages, especially with 50x errors, where we do not want to show the client sensitive information from failures.