【问题标题】:How to throw out of then-catch block?如何抛出 then-catch 块?
【发布时间】:2021-09-21 03:57:23
【问题描述】:

我目前正在研究如何从 then catch 块中抛出异常。我想了解errorHandler() 函数内部的问题。

const errorHandler = function () {
  try {
    thisFunctionReturnsAnError().then(response => {
      console.log(response);
    });
  } catch (e) {
    console.log(e); //How to trigger this?
  }
};

const thisFunctionReturnsAnError = function () {
  return3()
    .then(value => {
      throw new Error('This is the error message.');
    })
    .catch(err => {
      //return Promise.reject('this will get rejected');
      throw err;
      //this one should somehow got to the catch that is located in the errorHandler() function. How to do this?
      //I know that this 'err' will be in the next catch block that is written here. This is not what i want.
    });
};

const return3 = async function () {
  return 3;
};

errorHandler();

我在 stackoverflow 上搜索了一段时间,但没有任何帮助。我确信这个问题经常被问到,但我找不到答案,很抱歉。

编辑: 在这里添加了另一个版本的代码,但它仍然不起作用

const errorHandler = async function () {
  try {
    thisFunctionReturnsAnError()
      .then(response => console.log(response))
      .catch(err => console.log(err));
  } catch (e) {
    //console.log(e); //How to trigger this?
  }
};

const thisFunctionReturnsAnError = function () {
  return3()
    .then(value => {
      throw new Error('This is the error message.');
    })
    .catch(err => {
      return Promise.reject(`Message is: ${err}`);
    });
};

const return3 = async function () {
  return 3;
};

errorHandler();

我将收到以下错误消息: 未捕获(承诺中)消息是:错误:这是错误消息。

【问题讨论】:

  • 异步方法的错误处理需要与传统方式不同,下面的链接可能对您有用。参考:itnext.io/error-handling-with-async-await-in-js-26c3f20bc06a
  • 感谢您的回答,但遗憾的是这并没有回答我的问题。您给定链接中的内容不处理我的情况。我投入了 .catch() 函数。您发布的网站未处理此问题。

标签: javascript exception try-catch


【解决方案1】:

您的代码无法执行,因为“thisFunctionReturnsAnError”没有返回 Promise。这意味着您不能在返回值上调用“then”。

    thisFunctionReturnsAnError().then(response => { // will not work

为什么不总是使用承诺?

const errorHandler = function () {
  thisFunctionReturnsAnError()
    .then((response) => {
      console.log(response);
    })
    .catch((error) => {
      console.log('errorHandler: Handle the error.');
    });
};

const thisFunctionReturnsAnError = function () {
  return return_Three()
    .then((value) => {
      throw new Error('This is the error message.');
    })
    .catch((err) => {
      //return Promise.reject('this will get rejected');
      throw err;
      //this one should somehow got to the catch that is located in the errorHandler() function. How to do this?
      //I know that this 'err' will be in the next catch block that is written here. This is not what i want.
    });
};

const return_Three = async function () {
  return 3;
};

errorHandler();

/*****JUST ANOTHER SYNTAX*******/
const secondErrorHandler = async function () {
  try {
    await thisFunctionReturnsAnError();
  } catch (error) {
    console.log('secondErrorHandler: Handle the error.');
  }
};

secondErrorHandler();

【讨论】:

  • 谢谢你的作品。但是为什么要写return return_Three()而不是return_Three()呢?
  • 这是必要的,因为你试图对它做出反应。 > thisFunctionReturnsAnError()。否则此函数在线返回“void”。
【解决方案2】:

您无法使用同步 try/catch 处理承诺拒绝。不要使用它,使用 .catch() 的 promise 方法,就像在你的 thisFunctionReturnsAnError 函数中一样。

在使用async/await 语法时,您可以使用try/catch 处理承诺拒绝(尽管在return3 中您已经这样做了,尽管没有必要):

async function errorHandler() { /*
^^^^^ */
  try {
    const response = await thisFunctionReturnsAnError();
//                   ^^^^^
    console.log(response);
  } catch (e) {
    console.log(e); // works
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-16
    • 2011-11-16
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多