/
ValidationError.ts
67 lines (53 loc) · 1.61 KB
/
ValidationError.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
import printValue from './util/printValue';
import toArray from './util/toArray';
let strReg = /\$\{\s*(\w+)\s*\}/g;
type Params = Record<string, unknown>;
export default class ValidationError extends Error {
value: any;
path?: string;
type?: string;
errors: string[];
params?: Params;
inner: ValidationError[];
static formatError(
message: string | ((params: Params) => string) | unknown,
params: Params,
) {
const path = params.label || params.path || 'this';
if (path !== params.path) params = { ...params, path };
if (typeof message === 'string')
return message.replace(strReg, (_, key) => printValue(params[key]));
if (typeof message === 'function') return message(params);
return message;
}
static isError(err: any): err is ValidationError {
return err && err.name === 'ValidationError';
}
constructor(
errorOrErrors: string | ValidationError | ValidationError[],
value?: any,
field?: string,
type?: string,
) {
super();
this.name = 'ValidationError';
this.value = value;
this.path = field;
this.type = type;
this.errors = [];
this.inner = [];
toArray(errorOrErrors).forEach((err) => {
if (ValidationError.isError(err)) {
this.errors.push(...err.errors);
this.inner = this.inner.concat(err.inner.length ? err.inner : err);
} else {
this.errors.push(err);
}
});
this.message =
this.errors.length > 1
? `${this.errors.length} errors occurred`
: this.errors[0];
if (Error.captureStackTrace) Error.captureStackTrace(this, ValidationError);
}
}