简体   繁体   English

快速处理快速,同时管道流到响应

[英]Error handling in express while piping stream to response

I'm having some problem with handling errors in a Express js app. 我在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: 我正在使用errorHandler中间件,在路由中间件之后配置:

...
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 . 如果我在函数体中抛出TEST ERROR ,它将由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. 无论如何,如果在流中发出错误事件,则会调用错误事件处理程序,因为我可以在控制台中看到该消息,但是从不调用errorHandler

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. 如果我处理它,服务器向客户端发送500响应,但不调用errorHandler ,所以我错过了日志中的堆栈跟踪。

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). 一旦folderStream开始将数据folderStream到响应中, errorHandler就会在next(err)调用时无法编写folderStream

In that case, the browser (or http client) received a cancelled response. 在这种情况下,浏览器(或http客户端)收到取消的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM