-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy patherror.ts
More file actions
72 lines (62 loc) · 2.13 KB
/
error.ts
File metadata and controls
72 lines (62 loc) · 2.13 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
const errorRe =
/(Code|Error): (?<code>\d+).*Exception: (?<message>.+)\((?<type>(?=.+[A-Z]{3})[A-Z0-9_]+?)\)/s
interface ParsedClickHouseError {
message: string
code: string
type?: string
}
/** An error that is thrown by the ClickHouse server. */
export class ClickHouseError extends Error {
readonly code: string
readonly type: string | undefined
constructor({ message, code, type }: ParsedClickHouseError) {
super(message)
this.code = code
this.type = type
// Set the prototype explicitly, see:
// https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, ClickHouseError.prototype)
}
}
export function parseError(input: string | Error): ClickHouseError | Error {
const inputIsError = input instanceof Error
const message = inputIsError ? input.message : input
const match = message.match(errorRe)
const groups = match?.groups as ParsedClickHouseError | undefined
if (groups) {
return new ClickHouseError(groups)
} else {
return inputIsError ? input : new Error(input)
}
}
export function getCurrentStackTrace(): string {
const originalStackTraceLimit = Error.stackTraceLimit
Error.stackTraceLimit = 100
const stack = new Error().stack
Error.stackTraceLimit = originalStackTraceLimit
if (!stack) return ''
let foundNewLines = 0
let idx = 0
// Skip the first three lines of the stack trace, containing useless information
// - Text `Error`
// - Info about this function call
// - Info about the originator of this function call, e.g., `request`
while (foundNewLines < 3) {
idx = stack.indexOf('\n', idx + 1)
if (idx === -1) {
return ''
} else {
foundNewLines++
}
}
return stack.substring(idx + 1)
}
export function addStackTrace<E extends Error>(err: E, stackTrace: string): E {
if (err.stack) {
const firstNewlineIndex = err.stack.indexOf('\n')
const firstLine = err.stack.substring(0, firstNewlineIndex)
const errStack = err.stack.substring(firstNewlineIndex + 1)
err.stack = `${firstLine}\n${stackTrace}\n${errStack}`
}
return err
}