【问题标题】:Why isn't my error handler handling exceptions thrown from async middleware?为什么我的错误处理程序不能处理异步中间件抛出的异常?
【发布时间】:2021-01-19 04:48:55
【问题描述】:

如果我有一个中间件,我通常会抛出这样的错误:

function throwMiddleware(req, res, next) {
  throw new Error(`Something went wrong in your async middleware.`);
}

这将被我的集中式错误处理中间件捕获。

但是,当我有一个异步中间件时,我会得到一个 UnhandledPromiseRejectionWarning

async function throwMiddleware(req, res, next) {
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, 200);
  });
  throw new Error(`Something went wrong in your async middleware.`);
}

完整代码:

const express = require("express");

const app = express();
async function throwMiddleware(req, res, next) {
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, 200);
  });
  throw new Error(`Something went wrong in your async middleware.`);
}

app.get("/", throwMiddleware, (req, res, next) => { // route for GET /
  console.log("get /");
});

app.use((err, req, res, next) => { // centralized error handler
  if (res.headersSent) {
    return next(err);
  }

  console.log("error caught in middleware:", err.message);
  return res.send("oops");
});

app.listen(3500);

【问题讨论】:

    标签: node.js express asynchronous error-handling async-await


    【解决方案1】:

    throwing 的错误我把它放在next 调用中。但我不知道为什么 throwing 在同步中间件中有效,而在异步中间件中无效。

    async function throwMiddleware(req, res, next) {
      await new Promise((resolve) => {
        setTimeout(() => {
          resolve();
        }, 200);
      });
      next(new Error(`Something went wrong in your async middleware.`));
    }
    

    【讨论】:

    • 投掷就像返回,只是报错。它们都停止了代码的执行。
    • 是的,但是为什么错误处理程序会捕获同步中间件而不是异步中间件抛出的错误?我认为它们在两者中的工作方式相同。
    【解决方案2】:

    您可以在 express 中编写自己的错误处理程序,see the documentation here.

    app.use(function (err, req, res, next) {
      console.error(err)
      res.status(500).send('this is handled error')
    })
    

    最后使用你的声明app.use

    【讨论】:

    • 这已经在原始帖子的代码中了。问题是它在使用异步中间件抛出错误时无法处理。
    • 我认为我的问题不清楚,所以我编辑了原始问题以澄清问题
    猜你喜欢
    • 2021-11-12
    • 2011-08-17
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 2011-04-07
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多