I'm having some problem with handling errors in a Express js app.
My problem is that I'm piping a stream to response, and I don't know what is the best method to handle error that could occur in the readable stream.
I'm using errorHandler middleware, configured just after route middleware:
...
app.use(app.router);
app.use(express.errorHandler());
...
And this is my route:
exports.folders = function(req, res, next) {
//throw new Error("TEST ERROR");
var path = decodeURIComponent(req.params.path),
foldersStream = wd.listFolders(path);
foldersStream.on("error",function(err){
console.log("STREAM ERROR")
console.dir(next.name)
return next(err);
});
res.setHeader("content-type", "application/json");
foldersStream.pipe(res);
};
If I throw the TEST ERROR
in the body of the function, it is handled as expected by express errorHandler
.
Anyway, if an error event is emitted in the stream, the error event handler get called, because I can see the message in console, but errorHandler
never get called.
If I don't handle the error event, the whole node process crash. If I handle it, the server send a 500 response to client, but errorHandler
is not called, so I miss the stack trace in the log.
What I'm doing wrong?
Your code is correct: the problem is that the resonse is partially returned when the error occured.
Once the folderStream
starts to pipe data into the response, the errorHandler
is unable to write your stacktrace when invoked by next(err).
In that case, the browser (or http client) received a cancelled response.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With