error.ts 2.1 KB
Newer Older
陈文彬 已提交
1 2
import store from '/@/store';
import { hotModuleUnregisterModule } from '/@/utils/helper/vuexHelper';
V
vben 已提交
3
import { VuexModule, getModule, Module, Mutation, Action } from 'vuex-module-decorators';
陈文彬 已提交
4 5

import { formatToDateTime } from '/@/utils/dateUtil';
V
vben 已提交
6 7
import { ErrorTypeEnum } from '/@/enums/exceptionEnum';
import { useSetting } from '/@/hooks/core/useSetting';
陈文彬 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

export interface ErrorInfo {
  type: ErrorTypeEnum;
  file: string;
  name?: string;
  message: string;
  stack?: string;
  detail: string;
  url: string;
  time?: string;
}
export interface ErrorState {
  errorInfoState: ErrorInfo[] | null;
  errorListCountState: number;
}

const NAME = 'error';
hotModuleUnregisterModule(NAME);
@Module({ dynamic: true, namespaced: true, store, name: NAME })
class Error extends VuexModule implements ErrorState {
V
vben 已提交
28
  // error log list
陈文彬 已提交
29
  errorInfoState: ErrorInfo[] = [];
V
vben 已提交
30 31

  // error log count
陈文彬 已提交
32 33 34 35 36 37 38 39 40 41 42 43
  errorListCountState = 0;

  get getErrorInfoState() {
    return this.errorInfoState;
  }

  get getErrorListCountState() {
    return this.errorListCountState;
  }

  @Mutation
  commitErrorInfoState(info: ErrorInfo): void {
V
vben 已提交
44
    const item = {
陈文彬 已提交
45 46
      ...info,
      time: formatToDateTime(new Date()),
V
vben 已提交
47 48
    };
    this.errorInfoState = [item, ...this.errorInfoState];
陈文彬 已提交
49 50 51 52 53 54 55
    this.errorListCountState += 1;
  }

  @Mutation
  commitErrorListCountState(count: number): void {
    this.errorListCountState = count;
  }
V
vben 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

  @Action
  setupErrorHandle(error: any) {
    const { projectSetting } = useSetting();
    const { useErrorHandle } = projectSetting;
    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);
  }
陈文彬 已提交
80 81
}
export const errorStore = getModule<Error>(Error);