15815213711
2024-08-26 67b8b6731811983447e053d4396b3708c14dfe3c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const Log = require('../log');
const Ps = require('../ps');
const Conf = require('../config/cache');
const Message = require('../message');
 
/**
 * 捕获异常
 */
exports.start = function() {
  this.uncaughtExceptionHandler();
  this.unhandledRejectionHandler();
}
 
/**
 * 当进程上抛出异常而没有被捕获时触发该事件,并且使异常静默。
 */
exports.uncaughtExceptionHandler = function() {
  process.on('uncaughtException', function(err) {
    if (!(err instanceof Error)) {
      err = new Error(String(err));
    }
 
    if (err.name === 'Error') {
      err.name = 'unhandledExceptionError';
    }
 
    Log.coreLogger.error(err);
 
    _devError(err);
 
    _exit();
  });
}
 
/**
 * 当进程上抛出异常而没有被捕获时触发该事件。
 */
exports.uncaughtExceptionMonitorHandler = function() {
  // process.on('uncaughtExceptionMonitor', function(err, origin) {
  //   if (!(err instanceof Error)) {
  //     err = new Error(String(err));
  //   }
   
  //   Log.coreLogger.error('uncaughtExceptionMonitor:',err);
  // });
}
 
/**
 * 当promise中reject的异常在同步任务中没有使用catch捕获就会触发该事件,
 * 即便是在异步情况下使用了catch也会触发该事件
 */
exports.unhandledRejectionHandler = function() {
  process.on('unhandledRejection', function(err) {
    if (!(err instanceof Error)) {
      const newError = new Error(String(err));
      // err maybe an object, try to copy the name, message and stack to the new error instance
      if (err) {
        if (err.name) newError.name = err.name;
        if (err.message) newError.message = err.message;
        if (err.stack) newError.stack = err.stack;
      }
      err = newError;
    }
    if (err.name === 'Error') {
      err.name = 'unhandledRejectionError';
    }
 
    Log.coreLogger.error(err);
 
    _devError(err);
 
    _exit();
  });
}
 
/**
 * 如果是子进程,发送错误到主进程控制台
 */
function _devError (err) {
  if (Ps.isForkedChild() && Ps.isDev()) {
    Message.childMessage.sendErrorToTerminal(err);
  }
}
 
/**
 * 捕获异常后是否退出
 */
function _exit () {
  let cfg = Conf.getValue('exception');
  if (!cfg) {
    return;
  }
 
  if (Ps.isMain() && cfg.mainExit == true) {
    _delayExit();
  } else if (Ps.isForkedChild() && cfg.childExit == true) {
    _delayExit();
  } else if (Ps.isRenderer() && cfg.rendererExit == true) {
    _delayExit();
  } else {
    // other
  }
}
 
/**
 * 捕获异常后是否退出
 */
function _delayExit() {
  // 等待日志等异步写入完成
  setTimeout(() => {
    process.exit();
  }, 1500)
}