有没有一种方法可以防止Node.js应用因异步功能错误而崩溃?

时间:2020-06-03 15:54:05

标签: node.js asynchronous error-handling

考虑我们正在使用以下模块:

//buggy-module.js
function asyncFunctionThatCrashes() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let a = bibi.tibi; // Error
      resolve('super');
    }, 500);
  });
}
module.exports = asyncFunctionThatCrashes;

在我们的项目中:

//our-project.js
const asyncFunctionThatCrashes = require('buggy-module');

router.get('/',
  async (req, res) => {
    try{
       const result = await asyncFunctionThatCrashes();
       res.status(200).send(result);
    } catch (e) {
      res.status(500).send(); // this will not happen
    }
 })

在这种情况下,应用程序崩溃(try...catch无济于事,因为该错误发生在异步函数中)。
有办法防止崩溃吗?

0 个答案:

没有答案