-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fatalError.ts
63 lines (56 loc) · 1.7 KB
/
fatalError.ts
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
import { printStackTrace } from 'yerror';
import { location, service } from './util.js';
import initDebug from 'debug';
const debug = initDebug('knifecycle');
export const FATAL_ERROR = '$fatalError';
/**
* Allow to manage processes lifecycle fatal
* errors.
*/
export type FatalErrorService = {
errorPromise: Promise<void>;
registerErrorPromise: (errorPromise: Promise<void>) => void;
unregisterErrorPromise: (errorPromise: Promise<void>) => void;
throwFatalError: (err: Error) => void;
};
async function initFatalError(): Promise<FatalErrorService> {
const errorPromises: Promise<void>[] = [];
let errorCatchStep = 0;
let rejectFatalError;
const errorPromise = new Promise<void>((_resolve, reject) => {
rejectFatalError = reject;
});
const throwFatalError = (err: Error) => {
debug('Handled a fatal error', printStackTrace(err));
rejectFatalError(err);
};
const handleErrorCatch = () => {
const currentStep = ++errorCatchStep;
Promise.all(errorPromises).catch((err: Error) => {
if (currentStep === errorCatchStep) {
throwFatalError(err);
} else {
debug(
`Ignored a fatal error ${currentStep}/${errorCatchStep}:`,
printStackTrace(err),
);
}
});
};
return {
errorPromise,
registerErrorPromise: (errorPromise: Promise<void>) => {
errorPromises.push(errorPromise);
handleErrorCatch();
},
unregisterErrorPromise: (errorPromise: Promise<void>) => {
errorPromises.filter((anErrorPromise) => anErrorPromise !== errorPromise);
handleErrorCatch();
},
throwFatalError,
};
}
export default location(
service(initFatalError, FATAL_ERROR, [], true),
import.meta.url,
);