简体   繁体   中英

How to handle async callback promise rejection?

Try to handle every exception in my async code (nodeJS, ExpressJS): Here is almost pseudo code. I use limiter (npm limiter) module with method removeTokens (num, callback(err,remainingRequest)). Big part of code is inside the callback, and I wanna catch and throw any error there to the handler, but for now the error inside callback is still marked as "unhandled exception" and I don't understand why.

app.post('/', async (req, res) => {
  try {
    ...
    return getAll();

    async function getAll () {
      limiter.removeTokens(1, async (err, remainingRequest) => {
        try {
          throw new Error('THROWN')
        } catch (error) {
          throw error
        }
      })
    }
  } catch (error) {
    console.log(error);
  }
});

You shouldn't pass async functions into things that don't expect them (unless you catch all errors, as you are with your app.post callback). Instead, give yourself a wrapper for limiter.removeTokens that returns a promise:

function removeTokens(limiter, id) {
    return new Promise((resolve, reject) => {
        limiter.removeTokens(id, (err, remainingRequest) => {
            if (err) {
                reject(err);
            } else {
                resolve(remainingRequest);
            }
        });
    });
}

(You might also look into util.promisify for that.)

Then:

app.post('/', async (req, res) => {
  try {
    ...
    await getAll(); // *** Or you might just use `removeTokens(limiter, 1)` directly here

    function getAll() {
      return removeTokens(limiter, 1);
    }
  } catch (error) {
    console.log(error);
  }
});

Here it is using removeTokens directly:

app.post('/', async (req, res) => {
  try {
    ...
    await removeTokens(limiter, 1);
  } catch (error) {
    console.log(error);
  }
});

Firstly if possible please share as much code as you can as then it is easy for us to debug where the problem might be. Coming you your question i think the problem is that in your try..catch block you are throwing the error instead of handling it with a reject . Below i have pasted a code block which you can try and let me know if it works for you. Please not the syntax might be different but the idea is that you have to reject the Promise in case of error.

`````````limiter.removeTokens(1, async (err, remainingRequest) => {
````````````try {
```````````````throw new Error('THROWN')
````````````} catch (error) {
```````````````return Promise.reject(error) //
````````````}
`````````})
``````}
```} catch (error) {
``````console.log(error);
```}
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM