/
base.ts
79 lines (70 loc) · 1.92 KB
/
base.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
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
import { getVersion } from './utils.js'
type BaseErrorParameters = {
docsPath?: string | undefined
docsSlug?: string | undefined
metaMessages?: string[] | undefined
} & (
| {
cause?: never | undefined
details?: string | undefined
}
| {
cause: BaseError | Error | undefined
details?: never | undefined
}
)
export type BaseErrorType = BaseError & { name: 'ViemError' }
export class BaseError extends Error {
details: string
docsPath?: string | undefined
metaMessages?: string[] | undefined
shortMessage: string
override name = 'ViemError'
version = getVersion()
constructor(shortMessage: string, args: BaseErrorParameters = {}) {
super()
const details =
args.cause instanceof BaseError
? args.cause.details
: args.cause?.message
? args.cause.message
: args.details!
const docsPath =
args.cause instanceof BaseError
? args.cause.docsPath || args.docsPath
: args.docsPath
this.message = [
shortMessage || 'An error occurred.',
'',
...(args.metaMessages ? [...args.metaMessages, ''] : []),
...(docsPath
? [
`Docs: https://viem.sh${docsPath}${
args.docsSlug ? `#${args.docsSlug}` : ''
}`,
]
: []),
...(details ? [`Details: ${details}`] : []),
`Version: ${this.version}`,
].join('\n')
if (args.cause) this.cause = args.cause
this.details = details
this.docsPath = docsPath
this.metaMessages = args.metaMessages
this.shortMessage = shortMessage
}
walk(): Error
walk(fn: (err: unknown) => boolean): Error | null
walk(fn?: any): any {
return walk(this, fn)
}
}
function walk(
err: unknown,
fn?: ((err: unknown) => boolean) | undefined,
): unknown {
if (fn?.(err)) return err
if (err && typeof err === 'object' && 'cause' in err)
return walk(err.cause, fn)
return fn ? null : err
}