Express – 函数原型toString()在error handling?

当我在Express上吐出HTMLstring,而不是JSON时,我遇到了一个长期的问题,当我们明确地试图强制JSON总是从服务器出来时,

事实certificate,这是我的error handling中间件的问题 – 我错过了下一个参数,例如:

这是失败的:

app.use(function (err, req, res) { res.status(err.status || 500).json({ error: 'sorry the API experienced an error serving your priority request' }); }); 

这performance正确:

 app.use(function (err, req, res, next) { res.status(err.status || 500).json({ error: 'sorry the API experienced an error serving your priority request' }); }); 

正如你所看到的,添加第四个参数'next'可以让Express识别出这是一个error handlingcallback函数。

我的问题是 – Express如何知道正在使用的第四个参数,更不用说参数的types? 我唯一的猜测是,Express使用Function.prototype.toString()来查看参数的数量。 或者他们是以另一种方式做的?

正如它在使用Function.length的注释中所写的那样

length是一个函数对象的一个​​属性,它指出函数需要多less个参数,即forms参数的个数。

下面是来自快递仓库的代码片段 :

 Layer.prototype.handle_error = function handle_error(error, req, res, next) { var fn = this.handle; if (fn.length !== 4) { // not a standard error handler return next(error); } try { fn(error, req, res, next); } catch (err) { next(err); } };