I've been tinkering with file upload streams and came across such scenario:
- something causes an error and this error is passed down to the custom error handler
- the custom error handler invokes
res.status(500).send(message)
- 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?
I've been tinkering with file upload streams and came across such scenario:
res.status(500).send(message)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
expresscode 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 withhttp.STATUS_CODESis out of question for me.After looking a bit further and experimenting, I've created such a snippet:
The bottom part is obviously copied from the
finalhandlerlib.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?