-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathconstructor.ts
52 lines (44 loc) · 1.82 KB
/
constructor.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
import { extendError } from "./extend-error";
import { normalizeArgs, normalizeOptions } from "./normalize";
import { toJSON as errorToJSON } from "./to-json";
import { ErrorLike, ErrorLikeConstructor, ErrorLikeConstructorClass, OnoConstructor, OnoOptions } from "./types";
const constructor = Ono as OnoConstructor;
export { constructor as Ono };
/**
* Creates an `Ono` instance for a specifc error type.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
function Ono<T extends ErrorLike>(ErrorConstructor: ErrorLikeConstructor<T>, options?: OnoOptions) {
options = normalizeOptions(options);
function ono<TError extends ErrorLike, TProps extends object>(...args: unknown[]) {
let { originalError, props, message } = normalizeArgs<TError, TProps>(args, options!);
// Create a new error of the specified type
let newError = new (ErrorConstructor as ErrorLikeConstructorClass<T>)(message);
// Extend the error with the properties of the original error and the `props` object
return extendError(newError, originalError, props);
}
ono[Symbol.species] = ErrorConstructor;
return ono;
}
/**
* Returns an object containing all properties of the given Error object,
* which can be used with `JSON.stringify()`.
*/
Ono.toJSON = function toJSON(error: ErrorLike) {
return errorToJSON.call(error);
};
/**
* Extends the given Error object with enhanced Ono functionality, such as nested stack traces,
* additional properties, and improved support for `JSON.stringify()`.
*/
Ono.extend = function extend(error: ErrorLike, originalError?: ErrorLike, props?: object) {
if (props || originalError instanceof Error) {
return extendError(error, originalError, props);
}
else if (originalError) {
return extendError(error, undefined, originalError);
}
else {
return extendError(error);
}
};