简体   繁体   English

如何在ExpressJS中触发路由器错误处理程序而不是默认错误处理程序

[英]How to trigger router error handler instead of default error handler in expressjs

My express app uses the default JSON body parser: 我的express应用使用默认的JSON正文解析器:

app.use(bodyParser.json());

Further down the app.js file I have my own router for building REST API routes: app.js文件的更下方,我有自己的路由器来构建REST API路由:

var api = require('./routes/api/index');
...
app.use('/api', api);

This router has an error handler, among other things: 该路由器具有错误处理程序,其中包括:

router.use(function (err, req, res, next) {
  debugger;
  res.status(err.code ? getParseErrorStatus(err.code) : res.status || 500).send({
    error: err.message
  });
});

Whenever the bodyParser throws an error while parsing the request body, I get my generic express error handler called: 每当bodyParser在解析请求主体时抛出错误时,我都会得到一个通用的表达错误处理程序,称为:

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res, next) {
    debugger;
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

This holds true even for calls to /api/* URLs that are caught by the API router. 即使对于API路由器捕获的对/api/* URL的调用,也是如此。

Instead of always calling the generic error handler, how can I make JSON parsing errors (caught by middleware up in the chain) call the error handler I've defined in the API router, if the URL is an API URL? 如果URL是API URL,那么我不怎么总是调用通用错误处理程序,而是如何使JSON解析错误(由链中的中间件捕获)调用我在API路由器中定义的错误处理程序?

Error handlers are called at the same router stack level. 错误处理程序在同一路由器堆栈级别被调用。 Since the bodyParser.json() is executed at the main/root/app layer, it will look for the first error handler at the main/root/app layer. 由于bodyParser.json()在main / root / app层执行,因此它将在main / root / app层寻找第一个错误处理程序。

So if you want to handle API body parsing errors, you will have to move your bodyParser.json() middleware to each of your routes/routers that require body parsing. 因此,如果要处理API主体解析错误,则必须将bodyParser.json()中间件移动到需要主体解析的每个路由/路由器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM