Alexander Mills
Alexander Mills

Reputation: 100270

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 -

it turns out it was a problem in my error handling middleware - I was missing the next argument, e.g.:

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.

my question is - how does Express know about the fourth argument being in place, or let alone the types of the arguments? My only guess is that Express is using Function.prototype.toString() to look at the number of arguments. Or are they doing it another way?

Upvotes: 2

Views: 168

Answers (1)

gevorg
gevorg

Reputation: 5055

As it is written in the comments it uses Function.length

length is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters.

and below is the code fragment from express repository:

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

Upvotes: 1

Related Questions