1 | "use strict";
|
2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
3 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
4 | return new (P || (P = Promise))(function (resolve, reject) {
|
5 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
6 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
7 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
8 | step((generator = generator.apply(thisArg, _arguments || [])).next());
|
9 | });
|
10 | };
|
11 | Object.defineProperty(exports, "__esModule", { value: true });
|
12 | const logger_1 = require("./logger");
|
13 | function catchErrors(closeHandlers = [], { exitOnUncaughtPromiseException = true, logger = logger_1.default.fatal.bind(logger_1.default), timeout = 30, } = {}) {
|
14 |
|
15 |
|
16 | const uncaughtExceptionHandler = (err) => __awaiter(this, void 0, void 0, function* () {
|
17 | logger(err, 'uncaught exception');
|
18 |
|
19 | if (timeout) {
|
20 | setTimeout(() => {
|
21 | logger('could not finish in time, forcefully exiting');
|
22 | process.exit(1);
|
23 | }, timeout * 1000).unref();
|
24 | }
|
25 | for (const handler of closeHandlers) {
|
26 | try {
|
27 | yield Promise.resolve(handler());
|
28 | }
|
29 | catch (err) {
|
30 | logger(err, 'failed to close resource');
|
31 | }
|
32 | }
|
33 | process.exit(1);
|
34 | });
|
35 | process.on('uncaughtException', uncaughtExceptionHandler);
|
36 |
|
37 |
|
38 | const unhandledRejectionHandler = (reason = {}, promise) => __awaiter(this, void 0, void 0, function* () {
|
39 | logger(reason, 'unhandled promise rejection');
|
40 |
|
41 | if (timeout) {
|
42 | setTimeout(() => {
|
43 | logger('could not finish in time, forcefully exiting');
|
44 | process.exit(1);
|
45 | }, timeout * 1000).unref();
|
46 | }
|
47 | for (const handler of closeHandlers) {
|
48 | try {
|
49 | yield Promise.resolve(handler());
|
50 | }
|
51 | catch (err) {
|
52 | logger(err, 'failed to close resource');
|
53 | }
|
54 | }
|
55 | if (exitOnUncaughtPromiseException) {
|
56 | process.exit(1);
|
57 | }
|
58 | });
|
59 | process.on('unhandledRejection', unhandledRejectionHandler);
|
60 | return () => {
|
61 | process.off('uncaughtException', uncaughtExceptionHandler);
|
62 | process.off('unhandledRejection', unhandledRejectionHandler);
|
63 | };
|
64 | }
|
65 | exports.default = catchErrors;
|
66 |
|
\ | No newline at end of file |