Skip to content

Commit

Permalink
Merge pull request #95 from restyjs/errors
Browse files Browse the repository at this point in the history
updated default error format
  • Loading branch information
satishbabariya authored Oct 5, 2020
2 parents 9aa6fce + e4e5eb3 commit a00e883
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 41 deletions.
31 changes: 10 additions & 21 deletions src/errors.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,15 @@
export class HTTPError extends Error {
statusCode: number;
export class Exception extends Error {
status: number = 500;
code?: string;

constructor(message: string, statusCode?: number) {
super();
this.statusCode = statusCode ?? 500;
this.message = message;
constructor(message: string, status: number = 500, code?: string) {
super(message);
this.message = code ? `${code}: ${message}` : message;
this.status = status;
this.code = code;
}
}

export class ValidationError extends HTTPError {
errors: Object;
export class HTTPError extends Exception { }

constructor(errors: object) {
var message = "Bad Request";
if (Array.isArray(errors)) {
message = [
"failed to validate",
errors.map((error) => error.property).join(", "),
].join(" ");
}
super(message);
this.statusCode = 400;
this.errors = errors;
}
}
export class ValidationError extends Exception { }
29 changes: 9 additions & 20 deletions src/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import express from "express";
import { HTTPError, ValidationError } from "./errors";
import { Exception, HTTPError, ValidationError } from "./errors";

export const NotFoundErrorHandler: express.RequestHandler = (
req: express.Request,
Expand All @@ -16,25 +16,14 @@ export const DefaultErrorHandler: express.ErrorRequestHandler = (
res: express.Response,
next: express.NextFunction
) => {
if (err instanceof ValidationError) {
res.status(400);
if (err instanceof Exception) {
res.status(err.status || 500);
res.json({
error: err,
errors: {
message: err.message,
},
});
return;
} else if (err instanceof HTTPError) {
res.status(err.statusCode);
res.json({
error: err,
});
return;
} else {
next(err);
}

res.status(500);
res.json({
error: {
statusCode: 500,
message: err.message ? err.message : err,
},
});
};
};

0 comments on commit a00e883

Please sign in to comment.