/
base.ts
99 lines (89 loc) 路 2.38 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { STATUS_CODES } from 'http';
interface ErrorOption {
cause?: Error;
status?: number;
}
interface Convertable {
[key: string]: string | number;
}
type ConvertString<T extends Convertable, Group extends string> = {
[P in keyof T]: P extends string
? T[P] extends number
? `${Uppercase<Group>}_${T[P]}`
: never
: never;
};
const codeGroup = new Set();
/**
* Register error group and code, return the standard ErrorCode
* @param errorGroup
* @param errorCodeMapping
*/
export function registerErrorCode<T extends Convertable, G extends string>(
errorGroup: G,
errorCodeMapping: T
): ConvertString<T, G> {
if (codeGroup.has(errorGroup)) {
throw new MidwayError(
`Error group ${errorGroup} is duplicated, please check before adding.`
);
} else {
codeGroup.add(errorGroup);
}
const newCodeEnum = {} as Convertable;
// ERROR => GROUP_10000
for (const errKey in errorCodeMapping) {
newCodeEnum[errKey as string] =
errorGroup.toUpperCase() +
'_' +
String(errorCodeMapping[errKey]).toUpperCase();
}
return newCodeEnum as ConvertString<T, G>;
}
export class MidwayError extends Error {
code: number | string;
cause: Error;
constructor(message: string, options?: ErrorOption);
constructor(message: string, code: string, options?: ErrorOption);
constructor(message: string, code: any, options?: ErrorOption) {
super(message);
if (!code || typeof code === 'object') {
options = code;
code = 'MIDWAY_10000';
}
this.name = this.constructor.name;
this.code = code;
this.cause = options?.cause;
}
}
export type ResOrMessage = string | { message: string } | undefined;
export class MidwayHttpError extends MidwayError {
status: number;
constructor(resOrMessage: ResOrMessage, status: number);
constructor(
resOrMessage: ResOrMessage,
status: number,
code: string,
options?: ErrorOption
);
constructor(
resOrMessage: string | { message: string } | undefined,
status: number,
code?: string,
options?: ErrorOption
) {
super(
resOrMessage
? typeof resOrMessage === 'string'
? resOrMessage
: resOrMessage.message
: STATUS_CODES[status],
code ?? String(status),
options
);
if (resOrMessage && resOrMessage['stack']) {
this.stack = resOrMessage['stack'];
}
this.status = status;
}
}