在前端项目中使用了Ant Design,这个框架又使用了dva、umi、redux-saga。其中与后台的交互往往需要使用effects,例如
*fetchColumns(_, { call, put }) {
const data = yield call(fetchColumns);
yield put({
type: 'saveColumns',
payload: data,
});
},
*fetchSessionColumns(_, { call, put }) {
const data = yield call(fetchSessionColumns);
yield put({
type: 'saveSessionColumns',
payload: data,
});
},
此时如果后台服务器返回500错误,会导致call Effect抛出异常,最终会导致generator 停止运行。
解决的方法是可以加上try catch,例如
*fetchColumns(_, { call, put }) {
try{
const data = yield call(fetchColumns);
yield put({
type: 'saveColumns',
payload: data,
});
}catch (e) {
onError(e)
}
}
但是这样的话,需要每次调用时都try catch,因此需要统一异常处理。
Ant Design封装的是umi,umi封装了dva,dva封装了redux-saga。统一异常处理可以在umi中进行。官方文档中说明如下
在 src 目录下新建 app.js,内容如下:
export const dva = {
config: {
onError(e) {
e.preventDefault();
console.error(e.message);
},
}
};
本文介绍在使用AntDesign、umi和dva框架的前端项目中,如何统一处理与后台交互时产生的异常,避免generator因错误而停止运行。通过在src/app.js中配置dva的onError方法,可以实现全局异常捕获,提高应用的健壮性。
1278





