我正在尝试在我的http响应中捕获错误。我正在使用React-redux作为前端。因此,首先,我有一个简单的请求处理,在其中检查每个请求的状态,并根据状态代码返回响应或抛出错误:
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
return parseJSON(response).then(responseFormatted => {
const error = new Error(response.error);
error.response = response;
error.response.payload = responseFormatted;
throw error;
});
}
我认为我的错误将是来自响应的正文json的response.error
。我的身体看起来像:
{
error:"Bad Request",
message:"Validation failed for object='loginRequest'. Error count: 2",
status:400,
timestamp:"2029-02-03T08:58:34.838+0000"
}
稍后在我的redux-saga中,我尝试捕获此错误:
export function* func() {
try {
let requestURL = "some url";
const response = yield call(request, requestURL, { method: 'POST', body });
if (response.accessToken) {
'Authenticate'
}
} catch (error) {
console.log(error);
}
}
它将错误返回到我的控制台,即:
Error at eval line const error = new Error(response.error);
也许有人可以告诉我我做错了什么?
答案 0 :(得分:0)
获取(本机和polyfill)和库,例如Axios具有已经管理的catch功能,而无需进行错误代码管理,即IE:
// Example with AXIOS
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Example with FETCH
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
return response.blob();
}
throw new Error('Network response was not ok.');
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});