javascript 获取 API 错误处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50330795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fetch API error handling
提问by merko
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..
我想显示来自我的 API 的错误消息,问题是如果我检查,我无法到达该错误response.ok,它返回 Fetch 错误,而不是来自 API 的错误。
If I don't use if(response.ok)...it returns the error from API but it dispatches the success action.
如果我不使用if(response.ok)...它,它会从 API 返回错误,但它会调度成功操作。
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
})
})
}
回答by Amirmohammad Moradi
according to This Article:
根据本条:
Per MDN, the
fetch()API only rejects a promise when“a network error is encountered, although this usually means permissions issues or similar.”
Basically
fetch()will only reject a promise if the user is offline, or some unlikely networking error occurs, such a DNS lookup failure.
根据 MDN,
fetch()API 仅在以下情况下拒绝承诺“遇到网络错误,尽管这通常意味着权限问题或类似问题。”
基本上
fetch()只会在用户离线时拒绝承诺,或者发生一些不太可能的网络错误,例如 DNS 查找失败。
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) );
回答by Andreas Gelever
In order to extract API message from server in case of some error, you have to use the following idiom (which doesn't lie on the surface though), see link
为了在出现某些错误时从服务器提取 API 消息,您必须使用以下习语(尽管表面上并不存在),请参阅链接
fetch("http://localhost:8090/test/error", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then(result => {
//Here body is not ready yet, throw promise
if (!result.ok) throw result;
return result.json();
})
.then(result => {
//Successful request processing
console.log(result);
}).catch(error => {
//Here is still promise
console.log(error);
error.json().then((body) => {
//Here is already the payload from API
console.log(body);
});
})
Verbose - yes!, but does exactly what is needed.
详细 - 是的!,但正是需要的。

