-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathberror.ts
46 lines (39 loc) · 1.3 KB
/
berror.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
export class BError extends Error {
private firstStack: string | undefined = undefined
/**
* @param msg - A description of the error
* @param cause - If you are inside a `catch` block you can pass the caught error here
* @param metadata - An object containing any data that could be useful for debugging
*/
constructor(
msg: string,
cause?: Error,
public metadata?: Record<string, unknown>
) {
super(msg)
// Workaround for https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, BError.prototype)
if (cause != undefined) {
const subMessage = cause instanceof Error
? cause.message
: `non-error object thrown: ${JSON.stringify(cause)}`
this.message = `${this.message}: ${subMessage}`
if (!this.firstStack) {
this.firstStack = cause.stack
}
}
this.stack = this.firstStack
this.metadata = {
...(cause instanceof BError ? cause.metadata : {}),
...metadata
};
}
public log(...args: unknown[]) {
const noMetadata = !this.metadata || Object.entries(this.metadata).length === 0
if (noMetadata) {
console.error(this.message)
} else {
console.error(this.message, this.metadata)
}
}
}