aboutsummaryrefslogtreecommitdiff
path: root/src/errors/errorware.ts
blob: 27040e761fe01c15c9b7c8a985cbd3a8f4d1dec0 (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
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
import { NextFunction,  Request, Response } from 'express';

export interface ErrorResponseBlock {
	status: string;
	error: string;
	error_description?: string;
	user_message?: string;
	// tslint:disable-next-line:no-any
	error_data?: any;
}

export class RequestError extends Error {
	public static is(test: Object): test is RequestError {
		const err: RequestError = test as RequestError;
		return err.code !== undefined
			&& err.name !== undefined
			&& err.responseBlock !== undefined;
	}

	public code: number;
	public userMessage?: string;
	// tslint:disable-next-line:no-any
	public errorData?: any;

	public constructor(
		errCode: number = 500,
		errName: string = 'internal_server_error',
		errDescription?: string,
		errUserMessage?: string,
		// tslint:disable-next-line:no-any
		errData?: any
	) {
		super(errDescription);
		this.code = errCode;
		this.name = errName;
		this.userMessage = errUserMessage;
		this.errorData = errData;
	}

	public responseBlock(): ErrorResponseBlock {
		return {
			status: 'error',
			error: this.name,
			error_description: this.message,
			user_message: this.userMessage,
			error_data: this.errorData
		};
	}
}

export type Errorware =
	(err: Error, req: Request, res: Response, next: NextFunction) => void;

export const errorHandler: Errorware =
	(err: Error, req: Request, res: Response, next: NextFunction): void => {
	console.log(err);
	if (RequestError.is(err)) {
		res.status(err.code)
			.json(err.responseBlock());
	} else {
		res.send(err);
	}
};