简体   繁体   English

Javascript 尝试 Catch 与 Catch 链

[英]Javascript Try Catch vs Catch chain

I recently ran into a Javascript problem catching errors and thus crashing when exception thrown.我最近遇到了一个 Javascript 问题,捕获错误并因此在抛出异常时崩溃。

  • funcReturnPromise().then().catch()

I had to change this to:我不得不将其更改为:

try {
  funcReturnPromise().then()
} catch (e) {
  ...
}

Couldn't find a decent explanation for it, any JS wizards available to enlighten a JS peasant?找不到合适的解释,有没有 JS 向导可以启发 JS 农民?

If funcReturnPromise() can throw synchronously (which functions that return promises should generally never do), then you do have to catch that synchronous exception with try/catch as you discovered when using regular .then() .如果funcReturnPromise()可以同步抛出(返回 Promise 的函数通常不应该这样做),那么您必须使用 try/catch 捕获同步异常,正如您在使用常规.then()时发现的那样。

This is one place where async functions can hep you.这是async函数可以帮助您的一个地方。 For example, if you declare funcReturnPromise as async , then the synchronous exception it throws will automatically become a rejected promise and the caller won't ever be exposed to a synchronous exception.例如,如果您将funcReturnPromise声明为async ,那么它抛出的同步异常将自动成为被拒绝的 promise 并且调用者将永远不会暴露于同步异常。

Or, if the caller (your code here) uses await, then you can catch both sycnhronous exceptions and rejected promises with the same try/catch .或者,如果调用者(您的代码在这里)使用 await,那么您可以使用相同的try/catch捕获同步异常和被拒绝的承诺。

So, for example, you could do this:因此,例如,您可以这样做:

async function myFunc()
    try {
      let result = await funcReturnPromise();
      console.log(result);
    } catch (e) {
        // this catches both a rejected promise AND
        // a synchronously thrown exception
        console.log(e);
    }
}

As per the docs You can handle error like this:根据文档,您可以像这样处理错误:

try {
  funcReturnPromise.then(value => {
    console.log(value); // Success!
  }, reason => {
    console.error(reason); // Error!
  });
} catch (e) {
  console.error(e); // Error!
}

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

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