vue-vben-admin/src/store/modules/error.ts

82 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-09-28 20:19:10 +08:00
import store from '/@/store';
import { hotModuleUnregisterModule } from '/@/utils/helper/vuexHelper';
2020-10-18 21:55:21 +08:00
import { VuexModule, getModule, Module, Mutation, Action } from 'vuex-module-decorators';
2020-09-28 20:19:10 +08:00
import { formatToDateTime } from '/@/utils/dateUtil';
2020-10-18 21:55:21 +08:00
import { ErrorTypeEnum } from '/@/enums/exceptionEnum';
import projectSetting from '/@/settings/projectSetting';
2020-09-28 20:19:10 +08:00
export interface ErrorInfo {
type: ErrorTypeEnum;
file: string;
name?: string;
message: string;
stack?: string;
detail: string;
url: string;
time?: string;
}
2020-11-23 00:35:15 +08:00
2020-09-28 20:19:10 +08:00
export interface ErrorState {
errorInfoState: ErrorInfo[] | null;
errorListCountState: number;
}
2021-02-28 12:25:57 +08:00
const NAME = 'app-error';
2020-09-28 20:19:10 +08:00
hotModuleUnregisterModule(NAME);
@Module({ dynamic: true, namespaced: true, store, name: NAME })
class Error extends VuexModule implements ErrorState {
2020-10-30 21:32:05 +08:00
// error log list
2020-09-28 20:19:10 +08:00
errorInfoState: ErrorInfo[] = [];
2020-10-30 21:32:05 +08:00
// error log count
2020-09-28 20:19:10 +08:00
errorListCountState = 0;
get getErrorInfoState() {
return this.errorInfoState;
}
get getErrorListCountState() {
return this.errorListCountState;
}
@Mutation
commitErrorInfoState(info: ErrorInfo): void {
2020-10-18 21:55:21 +08:00
const item = {
2020-09-28 20:19:10 +08:00
...info,
time: formatToDateTime(new Date()),
2020-10-18 21:55:21 +08:00
};
this.errorInfoState = [item, ...this.errorInfoState];
2020-09-28 20:19:10 +08:00
this.errorListCountState += 1;
}
@Mutation
commitErrorListCountState(count: number): void {
this.errorListCountState = count;
}
2020-10-18 21:55:21 +08:00
@Action
setupErrorHandle(error: any) {
const { useErrorHandle } = projectSetting;
2020-10-18 21:55:21 +08:00
if (!useErrorHandle) return;
const errInfo: Partial<ErrorInfo> = {
message: error.message,
type: ErrorTypeEnum.AJAX,
};
if (error.response) {
const {
config: { url = '', data: params = '', method = 'get', headers = {} } = {},
data = {},
} = error.response;
errInfo.url = url;
errInfo.name = 'Ajax Error!';
errInfo.file = '-';
errInfo.stack = JSON.stringify(data);
errInfo.detail = JSON.stringify({ params, method, headers });
}
this.commitErrorInfoState(errInfo as ErrorInfo);
}
2020-09-28 20:19:10 +08:00
}
export const errorStore = getModule<Error>(Error);