javascript - 如何以正确的方式捕获异常? [初学者]

标签 javascript node.js express exception try-catch

有以下函数,它不捕获 MyException。

const myFunction = () => async (req, res, next) => {
  try {
    myHTTPRequest().then(async (response) => {
      if (response.data.results.length != 1) {
        throw new MyException('MyError');
      }
      res.end('All good');
    })
    .catch((error) => {
      throw error; //Doesn't work
    });
  } catch (error) {
    console.log('This block should catch MyException, but it doesn't');
    next(error);
  }
};

相反,应用程序将以下错误消息写入控制台

(node:45746) UnhandledPromiseRejectionWarning
(node:45746) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:45746) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

问题是,需要如何调整代码才能在预期的 Catch-Block 中捕获 MyException?

最佳答案

问题是你在混合 .then/.catchtry/catch .

如果要代码输入try/catchasync功能,你必须使用 await Promise 上的关键字.

您可以删除 .catch因为它什么都不做,所以你再次抛出错误,这导致了 UnhandledPromiseRejectionWarning

const myFunction = () => (req, res, next) => {
  try {
    const response = await myHTTPRequest();

    if (response.data.results.length != 1) {
      throw new MyException('MyError');
    }
    res.end('All good');

  } catch (error) {
    next(error);
  }
};

使用 .then/catch没有 async/await代码将是:

const myFunction = () => (req, res, next) => {

    myHTTPRequest().then((response) => {
      if (response.data.results.length != 1) {
        throw new MyException('MyError');
      }
      res.end('All good');
    })
    .catch((error) => {
      throw error;
       // It makes no sense to throw again in here
       // But I'm showing you how to handle it if you do
    })
    .catch(error => {
        next(error);
    })
};

当然是双.catch没有意义,你应该删除它,留下一个:

const myFunction = () => (req, res, next) => {

    myHTTPRequest().then((response) => {
      if (response.data.results.length != 1) {
        throw new MyException('MyError');
      }
      res.end('All good');
    })
    .catch(error => {
        next(error);
    })
};

关于javascript - 如何以正确的方式捕获异常? [初学者],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55500138/

相关文章:

node.js - NodeJS+Multer 上传图片到服务器?

javascript - 输入数组在 Angularjs 中作为 null 传递

javascript - jquery 从 iframe 访问 window.parent 的 data()

javascript - 无法将 db.countDocuments 中的数据存储在 mongoDB 中

php - 带有动态数据的气泡工具提示

node.js - express :找不到命令

node.js - 如何在 Node/Express 客户端中正确呈现服务器端错误?

node.js - 使用 Node.js 进行 AES192 加密

javascript - 运行 react-scripts start 后如何停止?

mysql - Message.Create 不是函数 sequelize cli