为什么我的错误处理程序不能处理异步中间件引发的异常?

时间:2020-10-03 22:47:16

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

如果我有中间件,我通常可以抛出这样的错误:

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);

2 个答案:

答案 0 :(得分:0)

throw的错误的理解,我将其放在next调用中。但是我不知道为什么在同步中间件而不是异步中间件中可以投掷。

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

答案 1 :(得分:0)

您可以用快递see the documentation here.

编写自己的错误处理程序
app.use(function (err, req, res, next) {
  console.error(err)
  res.status(500).send('this is handled error')
})

最后使用此声明app.use

相关问题