summary refs log tree commit diff
path: root/api/src/util/ApiError.ts
blob: c133e6e7a015e8f025ec329ba44dc55266f938a6 (plain) (blame)
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
export class ApiError extends Error {
	constructor(
		readonly message: string,
		public readonly code: number,
		public readonly httpStatus: number = 400,
		public readonly defaultParams?: string[]
	) {
		super(message);
	}

	withDefaultParams(): ApiError {
		if (this.defaultParams) return new ApiError(applyParamsToString(this.message, this.defaultParams), this.code, this.httpStatus);
		return this;
	}

	withParams(...params: (string | number)[]): ApiError {
		return new ApiError(applyParamsToString(this.message, params), this.code, this.httpStatus);
	}
}

export function applyParamsToString(s: string, params: (string | number)[]): string {
	let newString = s;
	params.forEach((a) => {
		newString = newString.replace("{}", "" + a);
	});
	return newString;
}