首页 > 解决方案 > 如何处理 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。两者都不能一起工作

标签: javascriptnode.jsexpresserror-handling

解决方案


您可以通过使用 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

});

推荐阅读