提取API错误处理

编程入门 行业动态 更新时间:2024-10-25 14:22:35
本文介绍了提取API错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想显示来自我的API的错误消息,问题是如果我检查 response.ok ,则无法到达该错误,它返回Fetch错误,而不是

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.

以下是示例登录操作:

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错误处理

本文发布于:2023-11-24 19:48:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626579.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!