繁体   English   中英

未处理的拒绝

[英]Unhandled Rejection

我正在尝试处理(node:29804) UnhandledPromiseRejectionWarning: test1 first throw ,有没有人知道我可以如何干净地处理它? 我对在这种情况下使用 await 不感兴趣。

const test0 = async () => {
  try {
    throw('test0 first throw');
  }
  catch(e) {
    console.log('test0 last catch');
    throw('test0 last throw');
  }
}

const test1 = async () => {
  try {
    test0()
    .catch(e => {
     console.log('test1 first catch');
     throw('test1 first throw'); // This throws unhandled exception
    })
//    return(0);
  }
  catch(e) {
    console.log('test1 last catch');
    throw('test1 last throw');
  }
}

const caller = async () => {
  try {
    let res = test1().
      catch(e => {
        console.log('PRE FINAL CATCH');
      })
    console.log(res);
  }
  catch(e) {
    console.log('FINAL CATCH');
//    console.log(e);
  }
}

caller();

混合使用try/catchthen()/catch() styles 处理 promise 有点少见。

您可以删除所有不必要的尝试/捕获并在需要的地方return 不涉及await 如果在其他函数的某处发生错误,它将被记录并返回给caller

 const test0 = async () => { try { throw('test0 first throw'); } catch(e) { console.log('test0 last catch'); throw('test0 last throw'); } } const test1 = async () => { return test0().catch(e => { console.log('test1 first catch'); throw('test1 first throw'); // This throws unhandled exception }); } const caller = async () => { return test1().catch((e) => { console.log('PRE FINAL CATCH'); }); } caller();

如果还有其他要求,我很乐意修改此答案。

感谢您的回复,我最终在这里阅读了有关异步错误处理如何工作的更多信息: https://medium.com/javascript-in-plain-english/javascript-async-function-error-handling-is-not-你怎么想dac10a98edb2

并最终采用了这种代码结构。 这个想法是如此具有类似的 function 结构和异步和等待函数的错误处理。 我更喜欢这个例子中的 try/catch 块的原因是因为它会捕获可能在 function 中的所有其他错误

// 如果你不能在调用者 function 中使用 await 则遵循结构 A

/************* 开始结构 A *************/

const handlerFnA = async(fnParam) => { await fnParam(); }

const fnDispatcherA = async () => {
  try{
    await handlerFnA(innerAsyncFnA);
  }
  catch (e){
    console.log('error caught in fnDispatcher: ', e);
  }
}

const innerAsyncFnA = async () => {
  try {
    throw('I am an error from innerAsyncFn');
  }
  catch(e) {
    console.log('innerAsyncFn catch');
    throw(e);
  }
}

const callerA = async () => {
  try {
    fnDispatcherA();
  }
  catch(e) {
    console.log('caller catch');
  }
}

/*********** 结束结构 A ************/

// 如果可以在调用者 function 中使用 await 则遵循结构 B

/************* 开始结构 B *************/

const handlerFnB = async(fnParam) => { await fnParam(); }

const innerAsyncFnB = async () => {
  try {
    throw('I am an error from innerAsyncFn');
  }
  catch(e) {
    console.log('innerAsyncFn catch');
    throw(e);
  }
}

const callerB = async () => {
  try {
    await handlerFnB(innerAsyncFnB);
  }
  catch(e) {
    console.log('caller catch');
  }
}

/*********** 结束结构 B ************/

callerB();

暂无
暂无

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

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