1

I'm using Nodejs.

I have a promise which request after a few seconds. But my Middleware not catches the error, but uncaughtException does.

router.all('/incaseoferror', async(req, res, next) => {

    const promise = await new Promise(function (resolve, reject) {
        setTimeout(function () {
            reject(new Error('this is a test err, the error-middleware NOT catch and it NOT OKAY'));
        }, 3000);
    });

  //  throw new Error('test error - the error-middleware catch it and that okay');
});

function clientErrorHandler(err, req, res, next) {

    console.log('in clientErrorHandler', err);
//but not catch the promise error!

});

process.on('uncaughtException', function (error) {

    // the error is catch here..
});

Here is the problem: Let's say I have login function from another library and it give me a promise. something has failed in the function, I cant catch the error in my error-middleware to give the user response that the request is failed.

  1. I dont want to add try/catch in every middleware. (route===middleware)
  2. I want use async/await
  3. Using uncaughtException not help me because I can't return response to the user in the route.

So what can I do? any ideas?

Shlomi Levi
  • 3,114
  • 1
  • 23
  • 35

1 Answers1

0

This should help you

await new Promise(function (resolve, reject) {
        setTimeout(function () {
            reject(new Error('this is a test err, the error-middleware NOT catch and it NOT OKAY'));
        }, 3000);
    })
.catch((err) => {
    clientErrorHandler(err);
 });
Rajkumar Somasundaram
  • 1,225
  • 2
  • 10
  • 20