是的,这在 Express 文档中的 Error Handling 下进行了解释。
Express 带有一个内置的错误处理程序,可以处理应用程序中可能遇到的任何错误。这个默认的错误处理中间件函数被添加到中间件函数栈的末尾。
如果您将错误传递给next(),并且您没有在自定义错误处理程序中处理它,它将由内置错误处理程序处理;错误将通过堆栈跟踪写入客户端。堆栈跟踪不包含在生产环境中。
文档没有详细介绍默认处理程序,但在looking at the source code 之后,默认处理程序是一个名为finalhandler 的单独模块。
无论如何,要覆盖此处理程序,请参阅 Express 文档中标题为 Writing error handlers 的部分。
它解释了:
以与其他中间件函数相同的方式定义错误处理中间件函数,除了错误处理函数有四个参数而不是三个:(err, req, res, next)。例如:
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
您最后定义错误处理中间件,在其他 app.use() 和路由调用之后
所以在你的情况下,如果你想用 400 来回应,你可以这样写:
const app = express();
const cors = require('cors')
var corsOptions = {
origin: function (origin: any, callback: any) {
if (!origin || whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(cors(corsOptions));
// This overrides the default error handler, and must be called _last_ on the app
app.use(function customErrorHandler(err, req, res, next) {
res.status(400).send('Your custom error message here');
});
在其 repo 中也表达includes a sample server,显示此错误处理覆盖。