如何在expressjs中触发路由器error handling程序而不是默认error handling程序

我的快车应用程序使用默认的JSON身体分析器:

app.use(bodyParser.json()); 

app.js文件的下面,我有自己的路由器来构buildREST API路由:

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

这个路由器有一个error handling程序,其中包括:

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

每当bodyParser在parsing请求体的时候抛出一个错误,我得到了我的通用expression式error handling程序:

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

即使调用API路由器捕获的/api/* URL也是如此。

如果URL是一个API URL,我怎样才能使JSONparsing错误(被链中的中间件捕获)调用我在API路由器中定义的error handling函数?

error handling程序在相同的路由器堆栈级别被调用。 由于bodyParser.json()是在主/ root / app层执行的,因此它将在主/ root / app层查找第一个error handling程序。

所以,如果你想处理API主体parsing错误,你将不得不把bodyParser.json()中间件移动到你需要正文parsing的每个路由/路由器。