So, the trivial thing. All we know that Express has built-in default error handler that expect four arguments (err, req, res, next) to handle "synchronous exceptions" like ReferenceError, TypeError, etc:
UPDATE: this question is Express-specific, not about how to catch unhandled exceptions/etc. I want to know how in the first code block Express can handle user-defined exception. Second example with async. exception doesn't directly belongs to this question.
const express = require('express')();
express.all('*', (req, res) => {
throw new Error('my own error');
res
.send('okay?');
});
express.use((err, req, res, next) => {
console.error(err.stack);
res
.status(503)
.send('Express is still up and running');
}).listen(3000);
But not this:
const express = require('express')();
express.all('*', (req, res) => {
process.nextTick(() => {
throw new Error('my own error');
});
res
.send('okay?');
});
express.use((err, req, res, next) => {
console.error(err.stack);
res
.status(503)
.send('Won\'t be executed');
}).listen(3000);
But I'm curious about the realization of this handler.
I can't find anything like
process.on('uncaughtException'... or domains/Promises/cluster.
Maybe I miss something.
Can anyone clarify?