我有一個API的異步調用,其中第二個.catch塊沒有被執行。
首先,我在utils文件中定義了主API調用函數,如下所示:
const getCustomer= (body) => {
return new Promise(resolve => {
fetch('/getCustomer', {
method: 'post',
body: JSON.stringify(body),
headers: {
Accept: "application/json"
Content-type: "application/json"
- },
})
.then(response => response.json())
.then(json => resolve(json))
.catch(err => console.log('error happened', err))
})
};
稍后在我的JSX文件中,我通過導入上面的函數來調用API。
getCustomer(myPayload).then(res => {
setCustomer(res)
}).catch(err => {
setShowError(true)
})
我試圖用setShowError顯示錯誤消息,但由于某種原因,我只能看到從utils文件夾拋出的console.log('error happened', err)
,在那里我定義了fetch函數。有沒有關于如何修復此行為并執行catch函數的想法
如果希望兩個
.catch
都執行,則需要在第一個內拋出,否則結果將是getCustomer
將始終返回一個解析的承諾。您還需要對Promise構造函數使用reject
參數。并確保以React代碼返回承諾調用:
雖然這是可能的,但如果可行,通常更好的方法是不捕獲下面的錯誤,而是讓調用方處理它。也不要使用顯式承諾構造反模式。
這是我想要的。除非您真的需要
setCustomer
本身來處理它,否則就讓錯誤滲透到它的調用者。