Blame view

src/store/modules/error.ts 2.08 KB
陈文彬 authored
1
2
import store from '/@/store';
import { hotModuleUnregisterModule } from '/@/utils/helper/vuexHelper';
vben authored
3
import { VuexModule, getModule, Module, Mutation, Action } from 'vuex-module-decorators';
陈文彬 authored
4
5

import { formatToDateTime } from '/@/utils/dateUtil';
vben authored
6
import { ErrorTypeEnum } from '/@/enums/exceptionEnum';
vben authored
7
import { useProjectSetting } from '/@/hooks/setting';
陈文彬 authored
8
9
10
11
12
13
14
15
16
17
18

export interface ErrorInfo {
  type: ErrorTypeEnum;
  file: string;
  name?: string;
  message: string;
  stack?: string;
  detail: string;
  url: string;
  time?: string;
}
vben authored
19
陈文彬 authored
20
21
22
23
24
25
26
27
28
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 {
vben authored
29
  // error log list
陈文彬 authored
30
  errorInfoState: ErrorInfo[] = [];
vben authored
31
32

  // error log count
陈文彬 authored
33
34
35
36
37
38
39
40
41
42
43
44
  errorListCountState = 0;

  get getErrorInfoState() {
    return this.errorInfoState;
  }

  get getErrorListCountState() {
    return this.errorListCountState;
  }

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

  @Mutation
  commitErrorListCountState(count: number): void {
    this.errorListCountState = count;
  }
vben authored
57
58
59

  @Action
  setupErrorHandle(error: any) {
vben authored
60
    const { useErrorHandle } = useProjectSetting();
vben authored
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    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);
  }
陈文彬 authored
80
81
}
export const errorStore = getModule<Error>(Error);