javascript - 异步函数try catch block 是否可以包装称为异步函数,这也可能引发错误?

标签 javascript asynchronous error-handling async-await

我有以下代码:

const getJSON = async function(url, errorMsg = 'Something went wrong') {
  return fetch(url).then(response => {
    if (!response.ok) throw new Error(`${errorMsg} (${response.status})`);

    return response.json();
  });
};

const outerFunc = async function() {
  try {
    let x = await getJSON();
  } catch (err) {
    console.log(err);
  }
}

outerFunc();
我试图在控制台中运行代码并得到一个错误:

VM60:2 Fetch API cannot load chrome://new-tab-page/undefined. URL scheme "chrome" is not supported.


我想了解包围** outerFunc **函数的try/catch块是否可以捕获将由调用的异步函数( asyncFunction )或 asyncFunction 引起的错误,应由他自己处理。我知道在Java中可以“传播”错误。 JS中正确的行为是什么?

最佳答案

通常,您希望在可以对错误做出一些有用的事情的时候捕获错误。通常,这不是调用API的关键点,而是调用栈中更远的地方。允许错误自然向上传播到可以合理处理的位置是一个好主意。
例如,在实际的应用程序中,如果有一个catch块仅由console.log组成,则通常(并非总是)指示错误应该在其他地方捕获。发生错误时,通常会想通知用户有问题,因此以下模式非常常见:

getAPI()
  .then(populateWithResults)
  .catch((error) => {
    const div = document.querySelector('.errors').appendChild(document.createElement('div'));
    div.textContent = 'There was an unexpected error: ' + error.message;
  });
getAPI不会自己捕获,而只是允许调用者处理可能的错误-类似于getJSON函数正在执行的操作。
通常,您只想在一个位置捕获错误,但是有时您可能想在多个地方捕获它-例如,子组件可能想在遇到错误时做一些特别的事情,但是它也想要通知 call 者有问题。在这种情况下,重新抛出该错误可能类似于:
const makeSubComponent = () => {
  const componentContainer = document.querySelector('.container');
  const populateSubComponent = () => {
    // ...
  };
  return getAPI()
    .then(populateSubComponent)
    .catch((error) => {
      componentContainer.textContent = 'Something went wrong...'
      throw error; // Inform the caller of makeSubComponent of the error
    });
};
允许makeSubComponent及其调用者处理可能的问题。

关于javascript - 异步函数try catch block 是否可以包装称为异步函数,这也可能引发错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65707238/

相关文章:

javascript - JavaScript(Vanilla,没有jQuery)-具有* Async * AJAX(XMLHttpRequest)调用的函数的行为与async相同?

c# - .NET 4.5 的异步功能是否也适用于 MySql 和其他数据库?

mysql - NodeJS mysql promise 返回未定义

Python 的 asyncio 是同步工作的

html - 单击文本文件并指向特定行号

validation - flutter 中的字符串未删除空格

javascript - IE8开发者工具调试器给出错误的异常信息

javascript - 计算数组中有多少个具有特定名称的条目并保存以供以后使用

javascript - 如何使用 Node-express 将页面 B 通过表单发布的数据渲染到页面 A?

javascript - 为什么 Javascript 控件无法在托管 Web 浏览器中加载?