Skip to content

Terminating request after handling an error #2765

Description

@fatfisz

I've been tinkering with file upload streams and came across such scenario:

  1. something causes an error and this error is passed down to the custom error handler
  2. the custom error handler invokes res.status(500).send(message)
  3. request is still not terminated
    This is caused by data waiting on the request to be handled. I want the request to terminated soon after 2 happens.

I've looked into the express code and noticed that there is a last handler I could pass the error to. The problem is, in "production" mode a generic error message would be sent to the user, whereas I'd prefer a custom message. Tampering with http.STATUS_CODES is out of question for me.

After looking a bit further and experimenting, I've created such a snippet:

app.use((err, req, res, next) => {
  // Print error
  console.error(err.stack);

  function write() {
    res.status(500).send('Internal server error - see logs for details');
  }

  if (req.complete) {
    return write();
  }

  // Terminate request if there is unsent data
  req.unpipe();
  req.on('end', write);
  req.resume();
});

The bottom part is obviously copied from the finalhandler lib.

My question (at last) is: can this be done a bit cleaner? Getting there wasn't that easy and the result looks a bit complicated. Did I miss something in the docs?

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions