Skip to content

Define error-handling middleware functions explicitly (without arity detection) #2896

Open
@feross

Description

@feross

I propose adding an explicit app.error method for defining error-handling middleware functions:

app.error(function(err, req, res, next) {
  res.status(500).send('Something broke!');
});

Instead of:

app.use(function(err, req, res, next) {
  res.status(500).send('Something broke!');
});

It's so easy to forget the next argument when it's not being used in the body of the function, and that changes the whole meaning of the middleware. express is one of the only packages that has this pattern. Others that used this pattern in the past (i.e. superagent) have since removed it.

Furthermore, this clashes with popular linting rules like ESLint's no-unused-vars rule which enforce that all named arguments must be used in the function body. Users who see this rule and remove the un-unsed next parameter will be unwittingly changing the behavior of their program.

No one expects removing an unused parameter to change the behavior of a program.

app.use(function(err, req, res, next /* <-- unused, guess I'll remove this... */) {
  res.status(500).send('Something broke!');
});

The four argument middleware convention should be deprecated in favor of app.error, but support for it could remain for a long time, or even indefinitely. I just want to be able to recommend that folks use app.error going forward.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions