【问题标题】:Why is my try-catch exception with nested async function not throwing?为什么我的带有嵌套异步函数的 try-catch 异常没有抛出?
【发布时间】:2021-03-03 03:33:03
【问题描述】:

我想获取一些图像,所以我编写了一个基于 Promise 的脚本来从选定的图像 url 获取图像。但是,当提供无效的 url 时,它应该返回“Get Error”。但是相反(如我所见),应用程序崩溃了,因此 try-catch 块不起作用。

const Jimp = require("jimp");

function rgba(source, width, height) {
  return new Promise((resolve, reject) => {
    try {
      resolve((async () => {
        const image = await Jimp.read(source);
        const resized = image.resize(width, height);
        const rgbaArray = [];

        for (y = 0; y < height; y++) {
          for (x = 0; x < width; x++) {
            rgbaArray.push(Jimp.intToRGBA(resized.getPixelColor(x, y)));
          };
        };

        return rgbaArray;
      })());
    } catch {
      reject("Get Error");
    };
  });
};

// Returns correct result.
rgba(
  "https://upload.wikimedia.org/wikipedia/commons/9/9e/SpaceX_Crew-1_Launch_%28NHQ202011150029%29.jpg", 
  50, 
  50
).then(resolve => {
  console.log(resolve);
}).catch(reject => {
  console.log(reject);
}); 

// App crashes instead of logging "Get Error."
rgba(
  "improper_url", 
  50, 
  50
).then(resolve => {
  console.log(resolve);
}).catch(reject => {
  console.log(reject);
}); 

【问题讨论】:

  • 尝试将 try/catch 放在 lambda 主体中。我对 js 不是很感兴趣,但在 Java 中,这可能是每个线程有不同处理程序的未捕获异常的情况
  • @Rogue 你所说的 lambda 是指异步函数吗?
  • 是的!抱歉,语言之间的术语再次混淆

标签: node.js es6-promise jimp


【解决方案1】:

使用 try...catch 直接处理 async/await 调用。

function rgba(source, width, height) {
  return new Promise(async (resolve, reject) => {
    try {
      const image = await Jimp.read(source);
      const resized = image.resize(width, height);
      const rgbaArray = [];
      for (y = 0; y < height; y++) {
        for (x = 0; x < width; x++) {
          rgbaArray.push(Jimp.intToRGBA(resized.getPixelColor(x, y)));
        }
      }
      resolve(rgbaArray);
    } catch {
      reject('Get Error');
    }
  });
}

或者,做你的工作,让调用者方法处理可能的异常:

async function rgba(source, width, height) {
  const image = await Jimp.read(source);
  const resized = image.resize(width, height);
  const rgbaArray = [];
  for (y = 0; y < height; y++) {
    for (x = 0; x < width; x++) {
      rgbaArray.push(Jimp.intToRGBA(resized.getPixelColor(x, y)));
    }
  }
  return rgbaArray;
}

在调用者方法中,您可以轻松处理错误:

async function handler() {
  try {
    const result = await rgba(/* args */);
  } catch (e) {
    console.error(e);
  }
}

按承诺处理:

function handlerPromise() {
  rgba(/* args */)
      .then(result => {
        console.log(result);
      })
      .catch(err => {
        console.error(err);
      });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 2011-09-16
    • 2011-12-12
    相关资源
    最近更新 更多