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 });
}
}
}
我用VSCode调试了错误内容,我发现它有axios请求信息(我的意思是,我99%确定axios会抛出错误,它就来了)
我的身体反应是这样的:
{"message":"User doesn't exist","stack":"Error: User doesn't exist"}
所以我试着用:
console.log(error.request.response.message);
但是不行,可能是我忘记了关于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 }});
}
所以对我来说,区别似乎是我访问error.response.status而不是error.request.response。
推荐阅读
- javascript - 制表符不是函数
- ruby - 如何获取简单 Sequel Dataset 对象的表名?
- here-api - HereMaps API 端点返回带有换行符的 json
- laravel - Laravel 邮政编码查询
- c# - 使用参数调用存储过程以返回列表
- sql - 数据大小与查询执行
- advanced-custom-fields - ACF 中继器字段仅显示一行
- liferay - 如果 liferay 放置 30 分钟然后更新,则会出现 CSRF 令牌错误
- android - 前台服务不适用于 Oreo (Android 8.1.0)
- java - 在谷歌数据存储中的不同实体之间级联重复属性更改的最佳实践?