carebdayrvis carebdayrvis - 3 months ago 21
Node.js Question

Stream error handling

I am using got to stream a request. New to streams, I am not sure what the best way to deal with errors is. Specifically this request might send a 403, which I would like to catch, and not pipe the response if there is an error.

got.stream(url)
.on("error", (e) => {
console.log(e)
})
.pipe(res)


In this example, the response will still get piped to
res
even if the response returned a
403
. What is the right way to keep the response from being piped, or is there a better or more idiomatic way to go about this?

Answer

I tried your code with url pointing to my blog. However, it seems that it doesn't care whether the error event is triggered or not if you call pipe on got instance.

So, here's the workaround:

got.stream(url)
  .on('response', response => {
    response.pipe(res); // pipe to express's res.
  })
  .on('error', err => {
    // handle error
  });

Instead of calling the pipe directly from got object, you can listen for a response event to pipe the response you got to another response stream.