Javascript 一旦承诺得到解决,如何传递捕获中的错误?
我有一个api调用。如果失败,我想得到一个错误。为什么错误出现在then()中而不是catch()中?如何从catch访问它?我不希望在then()中编写长函数,比如if!res&等 代码如下:Javascript 一旦承诺得到解决,如何传递捕获中的错误?,javascript,reactjs,asynchronous,error-handling,promise,Javascript,Reactjs,Asynchronous,Error Handling,Promise,我有一个api调用。如果失败,我想得到一个错误。为什么错误出现在then()中而不是catch()中?如何从catch访问它?我不希望在then()中编写长函数,比如if!res&等 代码如下: const postStuff=async()=>{ 试一试{ const res=wait ax.post(“/stuff”); 返回res; }捕捉(错误){ 返回新错误(); } }; 导出默认函数App(){ React.useffect(()=>{ postStuff() .then(res
const postStuff=async()=>{
试一试{
const res=wait ax.post(“/stuff”);
返回res;
}捕捉(错误){
返回新错误();
}
};
导出默认函数App(){
React.useffect(()=>{
postStuff()
.then(res=>console.log(“res”,res))
.catch(err=>console.log(“err”,err))
}, [])
返回(
你好,世界
);
}
由于捕获错误后才返回错误,因此它将不再到达useffect
中的catch
块
只需在catch块中抛出错误:
const postStuff=async()=>{
试一试{
常数res='bla';
抛出新错误();
返回res;
}捕捉(错误){
抛出新错误();
}
};
postStuff().then(res=>console.log('then',res))
.catch(err=>console.log('catch',err))
而不是从postStuff catch块内部返回,您需要抛出错误
const postStuff = async () => {
try {
const res = await ax.post("/stuff");
return res;
} catch (err) {
throw new Error();
}
};
为什么要从
ax.post()
捕获错误,然后抛出另一个错误(而不是返回…
)呢?因为我可以在一个地方处理错误,而不必每次在应用程序中使用此函数时重复代码。这样比较容易。