mer*_*rko 11 javascript error-handling fetch reactjs
我想显示来自我的 API 的错误消息,问题是如果我检查,我无法到达该错误response.ok,它返回 Fetch 错误,而不是来自 API 的错误。
如果我不使用if(response.ok)...它,它会从 API 返回错误,但它会调度成功操作。
这是示例,登录操作:
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
})
})
}Run Code Online (Sandbox Code Playgroud)
这是发送正确消息但作为成功操作而不是失败操作的操作代码。
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
})
})
}Run Code Online (Sandbox Code Playgroud)
Ami*_*adi 15
根据本条:
根据 MDN,
fetch()API 仅在以下情况下拒绝承诺“遇到网络错误,尽管这通常意味着权限问题或类似问题。”
基本上
fetch()只会在用户离线时拒绝承诺,或者发生一些不太可能的网络错误,例如 DNS 查找失败。
然后,您可以使用这部分代码来使用非网络错误处理并使您的代码更具可读性
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) );
Run Code Online (Sandbox Code Playgroud)
And*_*ver 11
为了在出现某些错误时从服务器提取 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);
});
})
Run Code Online (Sandbox Code Playgroud)
详细 - 是的!,但正是需要的。
使用以下解决方案可以处理JSON API 错误、通用 API 错误和通用获取错误
fetch("api/v1/demo", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"data": "demo"
})
})
.then(response => {
if (!response.ok) {
return Promise.reject(response);
}
return response.json();
})
.then(data => {
console.log("Success");
console.log(data);
})
.catch(error => {
if (typeof error.json === "function") {
error.json().then(jsonError => {
console.log("Json error from API");
console.log(jsonError);
}).catch(genericError => {
console.log("Generic error from API");
console.log(error.statusText);
});
} else {
console.log("Fetch error");
console.log(error);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30964 次 |
| 最近记录: |