carebdayrvis carebdayrvis - 1 year ago 118
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.
.on("error", (e) => {

In this example, the response will still get piped to
even if the response returned a
. 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 Source

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:
  .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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download