我正在尝试捕获 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);
也许有人可以告诉我我做错了什么?
Fetch(本机和 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);
});