Vin*_*ent 6 error-handling reactjs redux-saga axios
这对我来说是新的,我试图弄清楚如何在 axios 发生错误时使用 yield generator (redux-saga) 检索请求正文
这是我正在使用的一段代码:
function requestLogin(user: ILoginUserPayload) {
const loginUrl = `${config.apiUrl}/auth/logIn`;
return axios.post(loginUrl, user);
}
export default function* watchAuthAction(): IterableIterator<any> {
while (true) {
const { payload }: { payload: ILoginUserPayload} = yield take(TYPES.LOGIN_REQUEST);
console.log(`Payload`, payload);
try {
const response = yield requestLogin(payload);
console.log(`Response`, response);
} catch (error) {
// According to my debug, error.request contains all the axios info
console.log(error.request.response);
yield put({ type: TYPES.LOGIN_FAILURE, error: error.request.response.message });
}
}
}
Run Code Online (Sandbox Code Playgroud)
我用 VSCode 调试错误内容,发现里面有 axios 请求信息(我的意思是,我 99% 确定 axios 抛出错误并且它出现在这里)
我的身体反应是这样的:
{"message":"User doesn't exist","stack":"Error: User doesn't exist"}
Run Code Online (Sandbox Code Playgroud)
所以我尝试通过以下方式获取它:
console.log(error.request.response.message);
Run Code Online (Sandbox Code Playgroud)
但它不起作用,也许我忘记了一些关于 axios 的东西......
任何的想法?
编辑:我实际上正在阅读这部分:https : //github.com/axios/axios#handling-errors 但我仍然无法访问我的数据:/
你的代码似乎是正确的,对我来说唯一的区别是:
try {
const response = yield call(apiCall, action.payload)
yield put({ type: successReducer, payload: response });
} catch(error) {
// Construct an error message
let errorMessage = error.response.status + ":"+ error.response.statusText;
yield put({ type: failReducer, payload: { message : errorMessage }});
}
Run Code Online (Sandbox Code Playgroud)
所以对我来说,区别似乎是我访问了 error.response.status 而不是 error.request.response。
所以正如我所料,这是一个 axios 错误。
我只是按照文档获取数据:)
这是部分:
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
Run Code Online (Sandbox Code Playgroud)
就我而言,我只需要使用以下方式获取消息:
error.response.data.message
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3655 次 |
| 最近记录: |