Blame view

src/setup/error-handle/index.ts 4.4 KB
vben authored
1
2
3
4
/**
 * Used to configure the global error handling function, which can monitor vue errors, script errors, static resource errors and Promise errors
 */
vben authored
5
import { errorStore, ErrorInfo } from '/@/store/modules/error';
vben authored
6
import { useProjectSetting } from '/@/hooks/setting';
vben authored
7
8
import { ErrorTypeEnum } from '/@/enums/exceptionEnum';
import { App } from 'vue';
vben authored
9
10
11
12
13

/**
 * Handling error stack information
 * @param error
 */
vben authored
14
15
16
17
18
function processStackMsg(error: Error) {
  if (!error.stack) {
    return '';
  }
  let stack = error.stack
vben authored
19
20
21
22
23
24
25
    .replace(/\n/gi, '') // Remove line breaks to save the size of the transmitted content
    .replace(/\bat\b/gi, '@') // At in chrome, @ in ff
    .split('@') // Split information with @
    .slice(0, 9) // The maximum stack length (Error.stackTraceLimit = 10), so only take the first 10
    .map((v) => v.replace(/^\s*|\s*$/g, '')) // Remove extra spaces
    .join('~') // Manually add separators for later display
    .replace(/\?[^:]+/gi, ''); // Remove redundant parameters of js file links (?x=1 and the like)
vben authored
26
27
28
29
30
31
32
  const msg = error.toString();
  if (stack.indexOf(msg) < 0) {
    stack = msg + '@' + stack;
  }
  return stack;
}
vben authored
33
34
35
36
/**
 * get comp name
 * @param vm
 */
vben authored
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function formatComponentName(vm: any) {
  if (vm.$root === vm) {
    return {
      name: 'root',
      path: 'root',
    };
  }

  const options = vm.$options as any;
  if (!options) {
    return {
      name: 'anonymous',
      path: 'anonymous',
    };
  }
  const name = options.name || options._componentTag;
  return {
    name: name,
    path: options.__file,
  };
}
vben authored
59
60
61
62
/**
 * Configure Vue error handling function
 */
vben authored
63
64
65
66
67
68
69
70
71
72
73
74
75
function vueErrorHandler(err: Error, vm: any, info: string) {
  const { name, path } = formatComponentName(vm);
  errorStore.commitErrorInfoState({
    type: ErrorTypeEnum.VUE,
    name,
    file: path,
    message: err.message,
    stack: processStackMsg(err),
    detail: info,
    url: window.location.href,
  });
}
vben authored
76
77
78
/**
 * Configure script error handling function
 */
vben authored
79
80
81
82
83
84
85
86
87
88
export function scriptErrorHandler(
  event: Event | string,
  source?: string,
  lineno?: number,
  colno?: number,
  error?: Error
) {
  if (event === 'Script error.' && !source) {
    return false;
  }
vben authored
89
90
91
  const errorInfo: Partial<ErrorInfo> = {};
  colno = colno || (window.event && (window.event as any).errorCharacter) || 0;
  errorInfo.message = event as string;
vben authored
92
  if (error?.stack) {
vben authored
93
94
95
96
97
98
99
100
101
102
103
104
105
    errorInfo.stack = error.stack;
  } else {
    errorInfo.stack = '';
  }
  const name = source ? source.substr(source.lastIndexOf('/') + 1) : 'script';
  errorStore.commitErrorInfoState({
    type: ErrorTypeEnum.SCRIPT,
    name: name,
    file: source as string,
    detail: 'lineno' + lineno,
    url: window.location.href,
    ...(errorInfo as Pick<ErrorInfo, 'message' | 'stack'>),
  });
vben authored
106
107
108
  return true;
}
vben authored
109
110
111
/**
 * Configure Promise error handling function
 */
vben authored
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
function registerPromiseErrorHandler() {
  window.addEventListener(
    'unhandledrejection',
    function (event: any) {
      errorStore.commitErrorInfoState({
        type: ErrorTypeEnum.PROMISE,
        name: 'Promise Error!',
        file: 'none',
        detail: 'promise error!',
        url: window.location.href,
        stack: 'promise error!',
        message: event.reason,
      });
    },
    true
  );
}
vben authored
130
131
132
/**
 * Configure monitoring resource loading error handling function
 */
vben authored
133
function registerResourceErrorHandler() {
vben authored
134
  // Monitoring resource loading error(img,script,css,and jsonp)
vben authored
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
  window.addEventListener(
    'error',
    function (e: Event) {
      const target = e.target ? e.target : (e.srcElement as any);

      errorStore.commitErrorInfoState({
        type: ErrorTypeEnum.RESOURCE,
        name: 'Resouce Error!',
        file: (e.target || ({} as any)).currentSrc,
        detail: JSON.stringify({
          tagName: target.localName,
          html: target.outerHTML,
          type: e.type,
        }),
        url: window.location.href,
        stack: 'resouce is not found',
        message: (e.target || ({} as any)).localName + ' is load error',
      });
    },
    true
  );
}
vben authored
158
159
160
161
/**
 * Configure global error handling
 * @param app
 */
vben authored
162
export function setupErrorHandle(app: App) {
vben authored
163
  const { useErrorHandle } = useProjectSetting();
vben authored
164
165
  if (!useErrorHandle) return;
  // Vue exception monitoring;
vben authored
166
  app.config.errorHandler = vueErrorHandler;
vben authored
167
168

  // script error
vben authored
169
  window.onerror = scriptErrorHandler;
vben authored
170
171

  //  promise exception
vben authored
172
173
  registerPromiseErrorHandler();
vben authored
174
  // Static resource exception
vben authored
175
176
  registerResourceErrorHandler();
}