【问题标题】:I'm unable to catch errors from an async functio我无法从异步函数中捕获错误
【发布时间】:2021-06-30 23:47:45
【问题描述】:

给定以下从后端更新值的函数:

const updateValues = async (arg1, arg2, arg3) => {
  try {
    const response = await axios.patch(
      ...
    );
    ...
    return response.data;
  } catch (err) {
    console.error(err.response);
    return {};
  }
};

我无法成功响应 Promise 函数,这是我的实现:

const response = updateValues('bar', id, value1, value2, 'foo'
);
response
  .then(() => console.log('success:', response))
  .catch((err) => console.log('fail:', err));

我得到的是,不管response 总是解决并且我永远不会发现错误,我做错了什么?

【问题讨论】:

  • 但是你的整个函数体都在try/catch里面,而catch所做的一切都是正常返回?
  • 问题是你的updateValues 函数永远不会抛出。它总是捕获任何 axios 错误并返回一个空对象。
  • 您可以将 return {}; 替换为 throw err; 以重新引发错误。见:jsfiddle.net/04jnzo5d
  • 使用 then/catch 时不使用 try/catch 会怎样?
  • 我无法控制后端代码,所以我想在这种情况下我无能为力

标签: javascript async-await promise


【解决方案1】:

因此,您需要决定要在哪里捕获抛出的错误。目前,您在 updateValues 函数中发现了错误。

如果你想处理 Axios 抛出的错误,你可以这样写函数:

const updateValues = async (arg1, arg2, arg3) => {
  const response = await axios.patch(...); // If Axios throws an error will propagate up to the caller
  ...
  // You could also throw other errors here manually if you'd like
  return response.data;
};

然后你可以在调用站点处理错误:

updateValues('bar', id, value1, value2, 'foo')
  .then((data) => console.log('success:', data))
  .catch((err) => console.log('fail:', err)); // Thrown exception handled here.

如果您想了解更多信息:Here's a good article on JS exceptions & best practices.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 2019-11-26
    • 2021-10-20
    • 2022-01-14
    • 2017-10-23
    • 2020-10-20
    • 2014-12-01
    • 2021-10-09
    相关资源
    最近更新 更多