aboutsummaryrefslogtreecommitdiff
path: root/src/errors/errorware.ts
diff options
context:
space:
mode:
authorjw2552018-03-03 14:53:31 +0000
committerjw2552018-03-03 14:53:31 +0000
commit0caebd4bfdfd9c8d7840fc379412d5d1f867575f (patch)
treeab0cd04004080d97bb85bde517f49d32eac9aedf /src/errors/errorware.ts
parentfixed compilation issues _2 (diff)
downloadmedicine-0caebd4bfdfd9c8d7840fc379412d5d1f867575f.tar.gz
medicine-0caebd4bfdfd9c8d7840fc379412d5d1f867575f.zip

pulled latest files from trh/payload-checker

Diffstat (limited to 'src/errors/errorware.ts')
-rw-r--r--src/errors/errorware.ts56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/errors/errorware.ts b/src/errors/errorware.ts
new file mode 100644
index 0000000..45a76b3
--- /dev/null
+++ b/src/errors/errorware.ts
@@ -0,0 +1,56 @@
+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 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
+ };
+ }
+}
+
+type Errorware =
+ (err: Error, req: Request, res: Response, next: NextFunction) => void;
+
+export const errorHandler: Errorware =
+ (err: Error, req: Request, res: Response, next: NextFunction): void => {
+ if ((err as RequestError).responseBlock) {
+ const rerr: RequestError = err as RequestError;
+ res.status(rerr.code)
+ .json(rerr.responseBlock());
+ } else {
+ res.send(err);
+ }
+};