-
-
Notifications
You must be signed in to change notification settings - Fork 201
Expand file tree
/
Copy patherrors.ts
More file actions
259 lines (221 loc) · 6.64 KB
/
errors.ts
File metadata and controls
259 lines (221 loc) · 6.64 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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import * as util from "util";
import * as path from "path";
import * as _ from "lodash";
import { SourceMapConsumer } from "source-map";
import { isInteractive } from "./helpers";
import { deprecated } from "./decorators";
import { ErrorCodes, IErrors, IFailOptions } from "./declarations";
import { IInjector } from "./definitions/yok";
import { injector } from "./yok";
// we need this to overwrite .stack property (read-only in Error)
function Exception() {
/* intentionally left blank */
}
Exception.prototype = new Error();
async function resolveCallStack(error: Error): Promise<string> {
const stackLines: string[] = error.stack.split("\n");
const parsed = _.map(stackLines, (line: string): any => {
let match = line.match(/^\s*at ([^(]*) \((.*?):([0-9]+):([0-9]+)\)$/);
if (match) {
return match;
}
match = line.match(/^\s*at (.*?):([0-9]+):([0-9]+)$/);
if (match) {
match.splice(1, 0, "<anonymous>");
return match;
}
return line;
});
const fs = require("fs");
const remapped = await Promise.all(
_.map(parsed, async (parsedLine) => {
if (_.isString(parsedLine)) {
return parsedLine;
}
const functionName = parsedLine[1];
const fileName = parsedLine[2];
const line = +parsedLine[3];
const column = +parsedLine[4];
const mapFileName = fileName + ".map";
if (!fs.existsSync(mapFileName)) {
return parsedLine.input;
}
const mapData = JSON.parse(fs.readFileSync(mapFileName).toString());
return await SourceMapConsumer.with(mapData, null, (consumer) => {
const sourcePos = consumer.originalPositionFor({
line: line,
column: column,
});
if (sourcePos && sourcePos.source) {
const source = path.join(path.dirname(fileName), sourcePos.source);
return util.format(
" at %s (%s:%s:%s)",
functionName,
source,
sourcePos.line,
sourcePos.column
);
}
return util.format(
" at %s (%s:%s:%s)",
functionName,
fileName,
line,
column
);
});
})
);
let outputMessage = remapped.join("\n");
if (outputMessage.indexOf(error.message) === -1) {
// when fibers throw error in node 0.12.x, the stack does NOT contain the message
outputMessage = outputMessage.replace(/Error/, "Error: " + error.message);
}
return outputMessage;
}
export function installUncaughtExceptionListener(
actionOnException?: () => void
): void {
const handler = async (err: Error) => {
try {
let callstack = err.stack;
if (callstack) {
try {
callstack = await resolveCallStack(err);
} catch (err) {
console.error("Error while resolving callStack:", err);
}
}
console.error(callstack || err.toString());
await tryTrackException(err, injector);
if (actionOnException) {
actionOnException();
}
} catch (err) {
// In case the handler throws error and we do not catch it, we'll go in infinite loop of unhandled rejections.
// We cannot do anything here as even `console.error` may fail. So just exit the process.
process.exit(ErrorCodes.UNHANDLED_REJECTION_FAILURE);
}
};
process.on("uncaughtException", handler);
process.on("unhandledRejection", handler);
}
async function tryTrackException(
error: Error,
localInjector: IInjector
): Promise<void> {
let disableAnalytics: boolean;
try {
disableAnalytics = localInjector.resolve("staticConfig").disableAnalytics;
} catch (err) {
// We should get here only in our unit tests.
disableAnalytics = true;
}
if (!disableAnalytics) {
try {
const analyticsService = localInjector.resolve("analyticsService");
await analyticsService.trackException(error, error.message);
} catch (e) {
// Do not replace with logger due to cyclic dependency
console.error("Error while reporting exception: " + e);
}
}
}
export class Errors implements IErrors {
constructor(private $injector: IInjector) {}
public printCallStack: boolean = false;
public fail(optsOrFormatStr: string | IFailOptions, ...args: any[]): never {
const opts = this.getFailOptions(optsOrFormatStr);
return this.failWithOptions(opts, false, ...args);
}
@deprecated("Use `fail` instead.")
public failWithoutHelp(
optsOrFormatStr: string | IFailOptions,
...args: any[]
): never {
return this.fail(optsOrFormatStr, ...args);
}
public failWithHelp(
optsOrFormatStr: string | IFailOptions,
...args: any[]
): never {
const opts = this.getFailOptions(optsOrFormatStr);
return this.failWithOptions(opts, true, ...args);
}
private getFailOptions(optsOrFormatStr: string | IFailOptions): IFailOptions {
let opts = optsOrFormatStr;
if (_.isString(opts)) {
opts = { formatStr: opts };
}
return opts;
}
private failWithOptions(
opts: IFailOptions,
suggestCommandHelp: boolean,
...args: any[]
): never {
const argsArray = args || [];
const exception: any = new (<any>Exception)();
exception.name = opts.name || "Exception";
exception.message = util.format.apply(
null,
[opts.formatStr].concat(argsArray)
);
try {
const $messagesService = this.$injector.resolve("messagesService");
exception.message = $messagesService.getMessage.apply(
$messagesService,
[opts.formatStr].concat(argsArray)
);
} catch (err) {
// Ignore
}
exception.stack = new Error(exception.message).stack;
exception.errorCode = opts.errorCode || ErrorCodes.UNKNOWN;
exception.suggestCommandHelp = suggestCommandHelp;
exception.proxyAuthenticationRequired = !!opts.proxyAuthenticationRequired;
exception.printOnStdout = opts.printOnStdout;
this.$injector.resolve("logger").trace(opts.formatStr);
throw exception;
}
public async beginCommand(
action: () => Promise<boolean>,
printCommandHelpSuggestion: () => Promise<void>
): Promise<boolean> {
try {
return await action();
} catch (ex) {
const logger = this.$injector.resolve("logger");
const loggerLevel: string = logger.getLevel().toUpperCase();
const printCallStack =
this.printCallStack ||
loggerLevel === "TRACE" ||
loggerLevel === "DEBUG";
const message = printCallStack
? await resolveCallStack(ex)
: isInteractive()
? `\x1B[31;1m${ex.message}\x1B[0m`
: ex.message;
if (ex.printOnStdout) {
logger.info(message);
} else {
logger.error(message);
}
if (ex.suggestCommandHelp) {
await printCommandHelpSuggestion();
}
await tryTrackException(ex, this.$injector);
process.exit(
_.isNumber(ex.errorCode) ? ex.errorCode : ErrorCodes.UNKNOWN
);
}
}
// If you want to activate this function, start Node with flags --nouse_idle_notification and --expose_gc
verifyHeap(message: string): void {
if (global.gc) {
console.log("verifyHeap: '%s'", message);
global.gc();
}
}
}
injector.register("errors", Errors);