I'm trying to setup a Global error handler in Express where I can catch all the errors and return a custom error message, but I also want to remove the try/catch from all endpoints, going from this:
app.get('/', (req, res, next) => {
try {
throw new Error('BROKEN')
} catch (err) {
next(err)
}
})
to this:
app.get('/', (req, res, next) => {
throw new Error('BROKEN')
})
I have already tried to add thy express error handler below. However, it only gets called if I first catch the error on the route and pass the error on next()
.
app.use((err, req, res, next) => {
res.status(500).send('Something broke!')
})
I did reflect the code to have a function like catchAllError()
.
cons catchAllError = fn => (req, res, next) => {
try {
fn(req, res, next);
} catch {
next(err)
}
}
bring the footprint of all the endpoints down to:
app.get('/', catchAllError((req, res, next) => {
throw new Error('BROKEN')
}));
However now I want to remove the callback too.
I try to handle all global errors using
process.on('uncaughtException', (err) => {
console.log('What to do with the error now!');
});
However, even tho I can catch all the errors here I have no longer access to the req/res/next.
Any ideas on where to go from here to get all the exceptions caught and return with a custom message to the user without the need to add try/catch on all endpoints?