Fetch API error handling(获取 API 错误处理)
问题描述
我想显示来自我的 API 的错误消息,问题是如果我检查 response.ok
,我无法达到那个错误,它返回 Fetch 错误,而不是来自 API 的错误.
I want to display error message from my API, problem is that I can't reach that error if I check for response.ok
, it returns Fetch error, not the one from API..
如果我不使用 if(response.ok)...
它会从 API 返回错误,但会调度成功操作.
If I don't use if(response.ok)...
it returns the error from API but it dispatches the success action.
这里是示例,登录操作:
Here is the example, login action:
export const signIn = data => dispatch => {
dispatch({
type: SIGN_IN
})
fetch(API_URL+'/login', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(data),
})
.then( response => {
if (!response.ok) { throw response }
return response.json() //we only get here if there is no error
})
.then( json => {
dispatch({
type: SIGN_IN_SUCCESS, payload: json
}),
localStorage.setItem("token", 'Bearer '+json.token)
localStorage.setItem("user", JSON.stringify(json.user))
})
.catch( err => {
dispatch({
type: SIGN_IN_FAILED, payload: err
})
})
}
这是发送正确消息的操作代码,但作为成功操作,而不是失败操作..
This is the code for action that dispatches the right message but as success action, not as failed one..
export const signIn = data => dispatch => {
dispatch({
type: SIGN_IN
})
fetch(API_URL+'/login', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(data),
})
.then( response => response.json())
.then( json => {
dispatch({
type: SIGN_IN_SUCCESS, payload: json
}),
localStorage.setItem("token", 'Bearer '+json.token)
localStorage.setItem("user", JSON.stringify(json.user))
})
.catch( err => {
dispatch({
type: SIGN_IN_FAILED, payload: err
})
})
}
推荐答案
根据这篇文章 :
每个 MDN,fetch()
API 仅在
一个网络遇到错误,尽管这通常意味着权限问题或类似的."
"a network error is encountered, although this usually means permissions issues or similar."
基本上 fetch()
只会在用户拒绝承诺时离线,或发生一些不太可能的网络错误,例如 DNS查找失败.
Basically fetch()
will only reject a promise if the user
is offline, or some unlikely networking error occurs, such a DNS
lookup failure.
然后,您可以使用这部分代码来使用非网络错误处理并使您的代码更具可读性
then, you can use this part of code to use non-network error handlings and make your code more readable
function handleErrors(response) {
if (!response.ok) throw new Error(response.status);
return response;
}
fetch("API URL")
// handle network err/success
.then(handleErrors)
// use response of network on fetch Promise resolve
.then(response => console.log("ok") )
// handle fetch Promise error
.catch(error => console.log(error) );
这篇关于获取 API 错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取 API 错误处理


基础教程推荐
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 直接将值设置为滑块 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01