-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
65 lines (52 loc) · 1.73 KB
/
index.js
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
'use strict'
function defaultErrorHandler(error) {
console.error(error)
}
function getScriptArgs(process) {
if (!process || typeof process !== 'object' || !Array.isArray(process.argv)) {
return []
}
const [, , ...params] = process.argv
return params
}
function setExitCode(process, code = 1) {
if (process && typeof process === 'object' && process.exitCode !== code) {
process.exitCode = code
}
}
async function handleError(mainError, errorHandler) {
setExitCode(process, 1)
if (errorHandler === defaultErrorHandler) {
return defaultErrorHandler(mainError)
}
try {
await errorHandler(mainError)
} catch (errorHandlerFailure) {
console.warn(`The custom error handler failed`, errorHandlerFailure)
defaultErrorHandler(mainError)
}
}
function registerUnhandledRejectionHandler(process) {
if (!process || typeof process !== 'object' || typeof process.on !== 'function' || registerUnhandledRejectionHandler.done) {
return
}
function amUnhandledRejectionHandler(error, failedPromise) {
setExitCode(process, 2)
console.warn(`Unhandled Promise Rejection ${error}\n\tat: Promise ${failedPromise}`)
}
process.on('unhandledRejection', amUnhandledRejectionHandler)
registerUnhandledRejectionHandler.done = true
}
async function runMain(asyncMain, errorHandler, process) {
registerUnhandledRejectionHandler(process)
try {
return await asyncMain(...getScriptArgs(process))
} catch (mainError) {
await handleError(mainError, errorHandler)
}
}
function am(asyncMain, errorHandler = defaultErrorHandler) {
return runMain(asyncMain, errorHandler, process)
}
am.am = am
module.exports = am