Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 一旦承诺得到解决,如何传递捕获中的错误?_Javascript_Reactjs_Asynchronous_Error Handling_Promise - Fatal编程技术网

Javascript 一旦承诺得到解决,如何传递捕获中的错误?

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

我有一个api调用。如果失败,我想得到一个错误。为什么错误出现在then()中而不是catch()中?如何从catch访问它?我不希望在then()中编写长函数,比如if!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()
捕获错误,然后
抛出另一个错误(而不是
返回…
)呢?因为我可以在一个地方处理错误,而不必每次在应用程序中使用此函数时重复代码。这样比较容易。