javascript - 覆盖快速一般错误处理
问题描述
我正在尝试使用 json 对象覆盖表达一般错误处理,但它不起作用。
我测试它的方法是进行一个不存在路由的 http get 调用。
我添加了错误处理中间件,当我提出错误请求时,这仍然是返回的内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /api/image/initialize</pre>
</body>
</html>
这是“主要”功能:
async function main() {
// the startup initialization code, handle any initialization
// code in the startup folder, and call thh function in index.js
const {
settings,
projectCol
} = await initialize();
port = normalizePort(process.env.PORT || DEFAULT_PORT);
var app = express();
// view engine setup
app.use(logger('dev'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
// allow so it be used on the same PC
app.use( function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// setup routes
setupRoutes(app, { projectCol, settings });
app.set('port', port);
// error handling
app.use( function (err, req, res, next) {
if (res.headersSent) {
return next(err)
}
return res.status(500).json({
error: err.message
});
})
app.listen(port);
app.on('error', onError);
app.on('listening', onListening);
}
解决方案
我花了很长时间才弄清楚所以这里是可能会绊倒的人的答案。如果找不到路径,则必须添加一条全部捕获路由并将其转发给错误处理程序。
app.get('*', function(req, res, next) {
let err = new Error(`${req.originalUrl} doesn't exist`); // Tells us which IP tried to reach a particular URL
err.statusCode = 404;
err.shouldRedirect = true; //New property on err so that our middleware will redirect
next(err);
});
推荐阅读
- jenkins - SSH进入机器,检查文件是否存在,如果存在则让Jenkins执行shell失败
- linux - 在centos 7上安装veritas时,有人遇到过这个“找不到perl来执行./installer”吗?
- c++ - 优化剪裁功能
- javascript - AngularFireDatabase .auditTrail() 突然落后了一步
- javascript - 如何从元素内部获取父div?
- javascript - Javascript中具有递归的高阶函数
- python - 我需要在pygame中旋转时保持对象相对于自身向前移动
- r - 如何在 R 中排除月份以进行均值和标准差计算
- python - 有没有办法向量化这个函数或提高它的效率
- google-workspace - 已解决 - SDK 中的商品详情中缺少“英文”详细信息