Handle mongodb error while streaming directly to express response

I am just starting to use the mongodb stream function to stream data directly to express response .

To do this, I use the code snippet that is on this question :

cursor.stream().pipe(JSONStream.stringify()).pipe(res);

I want to mark a response with a state of 500 when the cursor returns a MongoError. Unfortunately, with this code, the error is returned in JSON with a status of 200.

How can I handle this with simple solutions? Should I handle this in case of a cursor error? If so, how can I say, not to transmit directly, to express an answer if an error has occurred?

EDIT

I tried the solution with handling the error event in the stream as follows:

var stream = cursor.stream();
stream.on('error', function(err){
    res.status(500).send(err.message);
});
stream.pipe(JSONStream.stringify()).pipe(res);

, , Error: write after end , .

, , ?

+4
1

WriteStream , ReadStream .

, - , . , {end: false} pipe.

, , , (, ).

var stream = cursor.stream();

stream.on('error', function () {
    res.status(500).send(err.message);
});

stream.on('end', function(){
  //Pipe does not end the stream automatically for you now
  //You have to end it manually
  res.end(); 
});

stream.pipe(res, {end:false}); //Prevent default behaviour

:
https://nodejs.org/dist/latest-v6.x/docs/api/stream.html#stream_readable_pipe_destination_options

+2

Source: https://habr.com/ru/post/1658918/


All Articles