Node.js未处理的拒绝错误

时间:2018-07-13 03:14:03

标签: javascript node.js promise

我的代码中出现未处理的拒绝错误,但跟踪不会告诉我是什么原因引起的。我认为是导致问题的webp.cwebp电话。运行代码时,我成功地转换了图像和日志状态,然后运行到未处理的拒绝中。似乎我没有进入最后两个.then(()块,因为没有任何控制台消息被记录下来。

如何正确处理拒绝错误以避免此错误?我尝试在statusresolve()语句中插入和删除reject(),但似乎无法解决。

 // Download image file from Google Cloud Storage bucket.
 return file.download({ destination: tempLocalFilename })
  .catch((err) => {
    console.error('Failed to download file.', err);
    return Promise.reject(err);
  })
  .then(() => {
    console.log(`Image ${file.name} has been downloaded to ${tempLocalFilename}.`);

    // Convert PNG to webp using webp-converter.
    return new Promise( (resolve, reject) => {
        webp.cwebp(tempLocalFilename, newLocalFilename, "-q 80", status => {
             console.log(status);

             if (status === '100') {
                 resolve();
             } else {
                 reject(status);
             }
           }
         );
       });
  })
  .then(() => {
    console.log(`Image ${file.name} has been converted.`);

    // Upload the converted image back into the bucket.
    return file.bucket.upload(newLocalFilename, { destination: file.name })
      .catch((err) => {
        console.error('Failed to upload converted image.', err);
        return Promise.reject(err);
      });
  })
  .then(() => {
    console.log(`Converted image has been uploaded to ${file.name}`);

    // Delete the temporary file.
    return new Promise((resolve, reject) => {
      fs.unlink(tempLocalFilename, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  });

1 个答案:

答案 0 :(得分:1)

问::我遇到未处理的拒绝错误,如何正确处理拒绝错误?

A:就像已经说过的话一样,.catch(...)将阻止您的异常冒充成为unhandled rejection error

或者,您也可以为每个.then(...)子句插入拒绝处理程序函数。也就是说,对于每个.then(),它应该具有2个函数,一个用于快乐路径,另一个用于坏路径。

例如

  return new Promise( (resolve, reject) => {
        webp.cwebp(tempLocalFilename, newLocalFilename, "-q 80", status => {
             ...
           }
         );
       });
  })
  .then(/*happy path=*/() => {
    console.log(`Image ${file.name} has been converted.`);

    // Upload the converted image back into the bucket.
    return file.bucket.upload(newLocalFilename, { destination: file.name })
      .catch((err) => {
        console.error('Failed to upload converted image.', err);
        return Promise.reject(err);
      });
  },
  /*unhappy path=*/ (error) => { 
      console.log("oops something went wrong during uploading"); 
  })
  /*catch all rejection=*/
  .catch(error => {
       console.log("something bad happened somewhere, rollback!");
   });