简体   繁体   English

Express - 错误处理中的函数原型 toString()?

[英]Express - function prototype toString() in error handling?

I had a longstanding issue with Express spitting out HTML strings instead of JSON, when we clearly were trying to force JSON to always come out of the server no matter what -我在 Express 吐出 HTML 字符串而不是 JSON 时遇到了一个长期问题,当时我们显然试图强制 JSON 总是从服务器中出来,无论如何 -

it turns out it was a problem in my error handling middleware - I was missing the next argument, eg:事实证明这是我的错误处理中间件中的一个问题 - 我错过了下一个参数,例如:

this was failing:这是失败的:

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

this was behaving correctly:这是正确的行为:

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

so as you can see, adding the fourth argument 'next' allowed Express to recognize this as an error handling callback function.如您所见,添加第四个参数“next”允许 Express 将其识别为错误处理回调函数。

my question is - how does Express know about the fourth argument being in place, or let alone the types of the arguments?我的问题是 - Express 如何知道第四个参数到位,更不用说参数的类型了? My only guess is that Express is using Function.prototype.toString() to look at the number of arguments.我唯一的猜测是 Express 正在使用 Function.prototype.toString() 来查看参数的数量。 Or are they doing it another way?或者他们正在以另一种方式这样做?

As it is written in the comments it uses Function.length正如它在评论中所写的那样,它使用Function.length

length is a property of a function object, and indicates how many arguments the function expects, ie the number of formal parameters. length是函数对象的一个​​属性,表示函数期望的参数数量,即形式参数的数量。

and below is the code fragment from express repository :下面是来自 express 存储库代码片段

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

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

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