【发布时间】:2021-01-02 15:09:22
【问题描述】:
我有一个 api 调用。万一它失败了,我想得到一个错误。为什么错误出现在then()中而不是catch()中?如何从 catch 访问它?我宁愿不必在 then() 中编写长函数,例如 if !res && 等。
代码如下:
const postStuff = async () => {
try {
const res = await ax.post("/stuff");
return res;
} catch (err) {
return new Error();
}
};
export default function App() {
React.useEffect(()=> {
postStuff()
.then(res=> console.log("res", res))
.catch(err=> console.log("err", err))
}, [])
return (
<div className="App">
hello world
</div>
);
}
【问题讨论】:
-
为什么将错误从
ax.post()捕获到throw(而不是return ...)另一个错误? -
因为我可以在一个地方处理我的错误,而不必每次在应用程序中使用此功能时重复一段代码。这样更容易。
标签: javascript reactjs asynchronous error-handling promise