B
B
Bogdan2019-11-01 20:38:26
Node.js
Bogdan, 2019-11-01 20:38:26

Global error handler for asynchronous errors?

Hello. Please tell me if it is possible to make a global middleware to catch asynchronous errors in Express.
Synchronized are excellent

routes.get('', (req, res) => { throw new Error('some-error'); }); // Эту ловит
app.use((err, req, res, next) => res.status(422).send(err.message));

and this one is no longer caught
routes.get('', async(req, res) => { throw new Error('some-error'); }); // Эту ловит
app.use((err, req, res, next) => res.status(422).send(err.message));

Of course, you can wrap each route in try {} catch {} , but can you do it differently? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RidgeA, 2019-11-01
@bogdan_uman

The fact is that express cannot work with promises out of the box, you need to make a middleware wrapper like https://medium.com/@Abazhenov/using-async-await-in...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question