0
votes

I have a multiple functions that return a Promise. In case of an error they use reject. But I want to handle the errors in the catch block of Promise.all() call. But when running it causes an Unhandled promise rejection.

function errorFunc() {
    return new Promise((_, reject) {
    reject('rejected in errorFunc')
  })
}

Promise.all([
    errorFunc(),
]).catch(reasons => {
    //throw new Error('an error occured', reasons)
  console.log('an error occured')
})

As you can see the console.log works fine, but running when throwing an exception it fails. I have read multiple articles and threads on unhandled promise rejection but I have not found a solution to that problem.

Here is the failing code on JSFiddle: https://jsfiddle.net/qkptbjnz/1/

How do I solve this issue? Or do you have a suggestion for a better error handling?

Edit I want to achieve some kind of validation like here: https://jsfiddle.net/89d5nLcw/

1
What's your goal here? You can handle the error in catch which is the intended way. No need to rethrow the errorJensV
@JensV I have a "validateObject" functions which calls multiple other validation functions asynchronously. When everythings done I want to throw an exception if one of them failed.ctwx
@JensV jsfiddle.net/89d5nLcw this is kind of the ideactwx
It works just like with try/catch: when you re-throw an exception from the catch block, you will have to catch that again somewhere else, or your program crashes.Bergi

1 Answers

2
votes

Well, you should not throw an error in catch section, this block is designed to handle the errors.

function errorFunc() {
    return new Promise((_resolve, reject) => {
    reject('rejected in errorFunc');
  });
}

Promise.all([
  errorFunc(),
]).catch(error => {
 console.log('an error occured', error);
})