如果我有中间件,我通常可以抛出这样的错误:
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);
答案 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
。