Gre*_*egg 12 reactjs redux react-redux axios
我正在使用axios
react/redux应用程序,当我收到401,404等错误时,我当前必须为每个动作函数处理它们,当我调用axios时.我有一个axios_config.js,我用一些常见的习语包裹了axios调用.例如:
// need to move this to app config
const BASE_URL = 'http://localhost:8080/api/';
function config() {
return {
headers: {'X-Token-Auth': localStorage.getItem('token')}
}
}
export function fetchData(url) {
return axios.get(`${BASE_URL}${url}`, config());
};
Run Code Online (Sandbox Code Playgroud)
我正在努力的是401,404等常见错误.目前,我这样做:
export function fetchBrands() {
return function(dispatch) {
dispatch({type:FETCHING_BRANDS});
fetchData('brands')
.then(response => {
dispatch({
type: FETCH_BRANDS_SUCCESS,
payload: response
});
})
.catch(err => {
// deal with errors
});
}
}
Run Code Online (Sandbox Code Playgroud)
但在catch
街区,我不想每次都要处理401,404等.因此,我需要能够在更全局范围内处理这些问题,但仍然能够处理请求的特定错误,例如服务器端验证错误.
小智 30
您可以使用响应拦截器作为axios文档中的文档.
axios.interceptors.response.use(undefined, function (error) {
if(error.response.status === 401) {
ipcRenderer.send('response-unauthenticated');
return Promise.reject(error);
}
});
Run Code Online (Sandbox Code Playgroud)
您可以尝试编写一个接受函数并返回附加了 catch 的函数的函数。您甚至可以传递可选的辅助参数来执行本地 catch 逻辑。
然后可以将其移动到单个文件中,并且您可以随时在那里修改它。
export function fetchBrand(id) {
return function (dispatch) {
wrapCatch(
fetchData(`brands/${id}`)
.then(response => {
dispatch({
type: FETCH_BRAND_SUCCESS,
payload: response
});
}),
function (err) {
// deal with errors
}
);
}
}
export function wrapCatch(f, localErrors) {
return f.catch(err => {
// deal with errors
localErrors();
});
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
归档时间: |
|
查看次数: |
7644 次 |
最近记录: |