简体   繁体   中英

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.');
      })
  );

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM