Search code examples
node.jserror-handlingnode-request

How to handle a URI error in node.js Request?


Trying to simply download a file with request. https://www.npmjs.com/package/request

It works perfectly fine, but if the url is invalid, the script crashes with the error: Invalid URI "notagoodurl"

How can I handle this error and log something and prevent the whole script from ending because of this error? I thought that's what on('error') would do.

//download file
request
  .get(url)
  .on('error', function(err) {
    return err;
  })
  .pipe(
    fs.createWriteStream(destination)
      .on('close', function() {
        message.channel.send(filename + ' added.');
      })
  );

Solution

  • If you need to work out fatal errors, then wrap the call into a catch:

    try {
      //download file
      request
        .get(url)
        .on('error', function(err) {
          console.log('Not a fatal error:', err);
        })
        .pipe(
          fs.createWriteStream(destination)
            .on('close', function() {
              message.channel.send(filename + ' added.');
            })
        );
    } catch (err) {
      console.log('Fatal error:', err);
    }