【发布时间】: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