diff options
| author | THarley | 2018-02-22 17:20:56 +0000 |
|---|---|---|
| committer | THarley | 2018-02-22 17:20:56 +0000 |
| commit | 0d917ec729ea8a54ae340033a3c95cc48f3cf6ea (patch) | |
| tree | b2dbed468410c5f1f7905775ed627c4b4aa4851b /src/errors/errorware.ts | |
| parent | Merge branch 'trh/yarn' into trh/payload-checker (diff) | |
| parent | Include error-handling in middleware stack (diff) | |
| download | medicine-0d917ec729ea8a54ae340033a3c95cc48f3cf6ea.tar.gz medicine-0d917ec729ea8a54ae340033a3c95cc48f3cf6ea.zip | |
Merge branch ‘trh/error-middleware’ into ‘trh/payload-checker’
Error-handling Middleware
See merge request cs3099group-be-4/project-code!14
Diffstat (limited to 'src/errors/errorware.ts')
| -rw-r--r-- | src/errors/errorware.ts | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/errors/errorware.ts b/src/errors/errorware.ts new file mode 100644 index 0000000..8b7e015 --- /dev/null +++ b/src/errors/errorware.ts @@ -0,0 +1,51 @@ +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: RequestError, req: Request, res: Response, next: NextFunction) => void; + +export const errorHandler: Errorware = + (err: RequestError, req: Request, res: Response, next: NextFunction): void => { + res.status(err.code) + .json(err.responseBlock()); +}; |
