简体   繁体   English

如何在 Promise 捕获块中引发异常? (未处理的 promise 拒绝)

[英]How to throw an exception in a Promise catch block? (Unhandled promise rejection)

I have a multiple functions that return a Promise.我有多个返回 Promise 的函数。 In case of an error they use reject .如果出现错误,他们会使用reject But I want to handle the errors in the catch block of Promise.all() call.但我想处理Promise.all()调用的 catch 块中的错误。 But when running it causes an Unhandled promise rejection .但是在运行时会导致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.如您所见, console.log工作正常,但在抛出异常时运行失败。 I have read multiple articles and threads on unhandled promise rejection but I have not found a solution to that problem.我已阅读有关未处理的 promise 拒绝的多篇文章和线程,但我还没有找到解决该问题的方法。

Here is the failing code on JSFiddle: https://jsfiddle.net/qkptbjnz/1/这是 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/编辑我想在这里实现某种验证: https://jsfiddle.net/89d5nLcw/

Well, you should not throw an error in catch section, this block is designed to handle the errors.好吧,你不应该在 catch 部分抛出错误,这个块是为了处理错误而设计的。

 function errorFunc() { return new Promise((_resolve, reject) => { reject('rejected in errorFunc'); }); } Promise.all([ errorFunc(), ]).catch(error => { console.log('an error occured', error); })
like here you can see the message you threw above. 像这里你可以看到你在上面抛出的消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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