-
Notifications
You must be signed in to change notification settings - Fork 678
Expand file tree
/
Copy pathhandle-errors.js
More file actions
84 lines (64 loc) · 2.26 KB
/
Copy pathhandle-errors.js
File metadata and controls
84 lines (64 loc) · 2.26 KB
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
import { UnhandledPromiseRejectionError, UncaughtExceptionError } from '../errors/test-run';
import util from 'util';
const runningTests = {};
let handlingTestErrors = false;
function printErrorMessagesAndTerminate (...messages) {
// eslint-disable-next-line no-console
messages.forEach(msg => console.log(msg));
// eslint-disable-next-line no-process-exit
setTimeout(() => process.exit(1), 0);
}
function handleTestRunError (ErrorCtor, message) {
Object.values(runningTests).forEach(testRun => {
testRun.addError(new ErrorCtor(message));
removeRunningTest(testRun);
});
}
function handleError (ErrorCtor, message) {
if (handlingTestErrors)
handleTestRunError(ErrorCtor, message);
else
printErrorMessagesAndTerminate(message);
}
function formatUnhandledRejectionReason (reason) {
const reasonType = typeof reason;
const isPrimitiveType = reasonType !== 'object' && reasonType !== 'function';
if (isPrimitiveType)
return String(reason);
if (reason instanceof Error)
return reason.stack;
return util.inspect(reason, { depth: 2, breakLength: Infinity });
}
export function formatError (ErrorCtor, error) {
if (ErrorCtor === UncaughtExceptionError)
return error.stack;
if (ErrorCtor === UnhandledPromiseRejectionError)
return formatUnhandledRejectionReason(error);
return error;
}
export function handleUnexpectedError (ErrorCtor, error) {
try {
const formattedError = typeof error === 'string' ? error : formatError(ErrorCtor, error);
handleError(ErrorCtor, formattedError);
}
catch (e) {
printErrorMessagesAndTerminate(error, e);
}
}
export function registerErrorHandlers () {
process.on('unhandledRejection', e => handleUnexpectedError(UnhandledPromiseRejectionError, e));
process.on('uncaughtException', e => handleUnexpectedError(UncaughtExceptionError, e));
}
export function addRunningTest (testRun) {
runningTests[testRun.id] = testRun;
}
export function removeRunningTest (testRun) {
if (testRun)
delete runningTests[testRun.id];
}
export function startHandlingTestErrors () {
handlingTestErrors = true;
}
export function stopHandlingTestErrors () {
handlingTestErrors = false;
}