首页 > 解决方案 > 覆盖快速一般错误处理

问题描述

我正在尝试使用 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);
}

标签: javascriptnode.jsexpress

解决方案


我花了很长时间才弄清楚所以这里是可能会绊倒的人的答案。如果找不到路径,则必须添加一条全部捕获路由并将其转发给错误处理程序。

  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);
  });

推荐阅读