快递:我怎样才能用下一步转发错误

Express: How can I forward errors with next

我想创建一个错误处理程序作为中间件。我的想法是当我没有得到任何匹配的路由时,我将生成一个“找不到路由错误”并使用 express 的 next() 参数。

我无法将生成的错误重定向到 errorHandler.js。里面不叫。我的错误在哪里?

app.js:

....
// after no matching routes call this
app.use((req, res, next) => {
    const err = new Error("route not found");
    res.status(404);
    next(err);
});

// call the error handler
app.use(errorHandler);

errorHandler.js:

import { Router, Request, Response, NextFunction } from "express";

    
const errorHandler = Router();

errorHandler.use(
    (
        err,req,res,next
    ) => {
        res.status(err.status || 500);
        res.json({
            error: {
                message: err.message,
                error: {},
            },
        });
    }
);

当我在 errorHandler.js 中使用它时: 输出略有不同:

errorHandler.use((req, res, next) => {
    const err = new Error("route not found");
    res.status(404);
    next(err);
});

为什么会这样?

errorHandler 应该是中间件,而不是路由器实例。您可以将 status 属性 添加到 err 对象并调用 next(err)err 转发到 errorHandler 中间件。集中设置错误处理器中间件的响应状态。

app.js:

import express from 'express';
import { errorHandler } from './errorHandler';
const app = express();

app.get('/', (req, res) => {
  res.sendStatus(200);
});

app.use((req, res, next) => {
  const err = new Error('route not found');
  err.status = 404;
  next(err);
});

app.use(errorHandler);

app.listen(3000, () => console.log('Server started at http://localhost:3000'));

errorHandler.js:

function errorHandler(err, req, res, next) {
  res.status(err.status || 500);
  res.json({
    error: {
      message: err.message,
      error: {},
    },
  });
}

export { errorHandler };

服务器日志:

⚡  curl http://localhost:3000       
OK%     
⚡  curl -i http://localhost:3000/api/v1
HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 50
ETag: W/"32-X7VodneZlwbfTuc/IPekfp/Xol0"
Date: Thu, 14 Jan 2021 10:01:07 GMT
Connection: keep-alive

{"error":{"message":"route not found","error":{}}}%