简体   繁体   中英

Node.js - throw exception inside ES6 promise chain

As part of an Node.js/Express API I am developing, I have built a custom error handler that lets me throw specific errors when needed eg BadRequest or NotFound etc.

The problem occurs when I wish to throw within a promise chain. For example:

db.doSomethingAsync().then(data => {

    if(data.length === 0){
        throw new errors.ResourceNotFound({ resource: "foo" });
    }
});

After much reading on the topic, I see that this error will be swallowed by the promise and hence causes an unhandled Promise rejection.

I am aware I can reject however im not sure how I can then handle the specific error (rather than a catchall on reject which I dont want).

Also, to reject, would I not need to create a new promise inside of my promise chain? That feels messy.

Can anyone advise how to handle throwing a specific exception within a promise chain?

In addition to the first callback to then() which is resolve callback and recieves data, you could also provide a second callback to it which is reject callback and it recieves errors. so you could catch this specific error on the second callback of the next then:

db
  .doSomethingAsync()
  .then(data => {
    if(data.length === 0){
        throw new errors.ResourceNotFound({ resource: "foo" });
    }
  })
  .then(massagedData => {
    // work with massagedData here
  }, err => {
    // handle err here which is previous thrown error
    // assert.ok( err instanceof errors.ResourceNotFound() )
  })
  .catch(err => {
    // this will catch unhandled errors if any
  });

then() by default returns a promise and if any of its callbacks ( whether the first or the second one ) throws an error then it returns a rejected promise and its reason will caught by next reject callback if any or by catch at the end. So you don't need to create a new promise.

See Promise.prototype.then()

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