Getz
Getz

Reputation: 4053

Handle mongodb error when streaming directly to express response

I just begin using the mongodb stream functionality to stream data directly to the express response.

For that, I use the piece of code that is found on this question:

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

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

How can I handle that using simple solutions? Do I have to handle that in the error event of the cursor? If so, how can I tell not to stream directly to express response if an error occurred?

EDIT

I've tried a solution with handling the error event on the stream like this:

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

Unfortunately, when an error occurred, I've got an Error: write after end from express because I've already sent the response in the error event.

How can I flag response with an error status when the cursor-stream failed AFTER I have piped it to response?

Upvotes: 3

Views: 1316

Answers (1)

tu4n
tu4n

Reputation: 4450

WriteStream is ended when ReadStream ends or has an error.

So you need to somehow prevent this default behaviour when errors happen during pipe. You can do that by passing {end: false} as pipe option.

This option alters default behavior so that even if the error occurs, your write stream is still open and you can keep sending more data down (e.g. error status).

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

More information can be found on:
https://nodejs.org/dist/latest-v6.x/docs/api/stream.html#stream_readable_pipe_destination_options

Upvotes: 2

Related Questions