javascript - 如何处理 express api 中的多个错误?就像我想处理 404,405,400 和 500
问题描述
因为我是 node.js 的新手,并且我使用 express 框架来构建 rest api。我想为我的 api 处理多个错误。就像我想处理 404,405,400 和 500。express 提供默认的错误处理程序。但我不明白它是如何工作的。所以我想构建自定义中间件来处理所有这些错误。
捕获 404 并转发到错误处理程序
app.use(function(req, res, next)
{
var err = new Error('URL Not Found');
err.status = 404;
next(err);
});
app.use(function(req, res, next) {
var err = new Error('Bad Request');
err.status = 400;
next(err);
});
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
err:{
message:err.message,
statuscode:err.status
}
})
res.render('error', {
message: err.message,
error: err
});
});
}
**production error handler no stacktraces leaked to user**
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
我已经处理了 404,400 和 500。但我无法处理 405 错误。我可以处理 404 或 405。两者都不能一起工作
解决方案
您可以通过使用 express 和 router 属性来做到这一点:
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
app.use(bodyParser.json());
mongoose
.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
.then(() => console.log("MongoDB Connected..."))
.catch(err => console.log(err));
router.post("/", (req, res) => {
const { data} = req.body; // This gets the data from the body of the request, using body-parser
if (!data) {
return res.status(400).json({ error: "Data should not be empty!" });
}
});
app.use("/")
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
借助 router 函数中的这条语句,您可以将带有 json 的错误状态传递给前端:
return res.status(400).json({ error: "Data should not be empty!" });
检查它:https ://expressjs.com/en/api.html#res.status
例如,使用错误处理中间件创建一个 error.js 文件:
const app = require('express');
const error = app.use(function (err, req, res, next) {
if (user == null || user == 'undefined') {
res.status(404);
}
next();
})
module.exports = error;
您现在可以在路由器功能中使用它,例如:
const error = require("../middleware/error");
router.post("/", error, (req, res) => {
const { data} = req.body; //now beacuse of the "error" in the parameters, if the request pass the error, than it will continue to this function
});
推荐阅读
- css - 通过 css 的文本装饰线在我的“已完成”类的 Safari 上不起作用
- hortonworks-sandbox - HDP 2.6.5 Sandbox 无法从本地访问
- codenameone - 模拟器挂起并且未连接到互联网时不显示任何错误
- hadoop -
- javascript - 带有 combineLatest 的 BehaviorSubject 的奇怪行为
- android - 将 google maps api 添加到 Android Studio 项目会导致 appcompat 出现问题
- android - 将数据提供给其他实际上不起作用的活动
- python-3.x - YouTube Livestream API - 提供标题时需要标题
- ember.js - EmberFire Google 身份验证 - 请查看设置
- java - 以编程方式选择指定项目时如何更改 RecyclerView 中项目的属性?