Skip to content
This repository has been archived by the owner on Aug 28, 2019. It is now read-only.

Commit

Permalink
fix: catch body-parser errors (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
michael1011 authored Apr 17, 2019
1 parent 549a524 commit 16f4622
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
14 changes: 12 additions & 2 deletions lib/api/Api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import cors from 'cors';
import express, { Application } from 'express';
import express, { Application, Request, Response, NextFunction } from 'express';
import Logger from '../Logger';
import Controller from './Controller';
import Service from '../service/Service';
Expand All @@ -17,11 +17,21 @@ class Api {

constructor(private logger: Logger, private config: ApiConfig, service: Service) {
this.app = express();
this.controller = new Controller(logger, service);

this.app.use(cors());
this.app.use(express.json());

this.controller = new Controller(logger, service);
// Catch the ugly errors generated by the body-parser
this.app.use((error: any, _req: Request, res: Response, next: NextFunction) => {
if (error instanceof SyntaxError) {
this.controller.errorResponse(res, error);
return;
}

next();
});

this.registerRoutes(this.controller);
}

Expand Down
8 changes: 6 additions & 2 deletions lib/api/Controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,15 @@ class Controller {
return response;
}

private errorResponse = (res: Response, error: any, statusCode = 400) => {
public errorResponse = (res: Response, error: any, statusCode = 400) => {
if (typeof error === 'string') {
this.invalidArgumentsResponse(res, statusCode, error);
} else {
this.invalidArgumentsResponse(res, statusCode, error.message);
if (error.details) {
this.invalidArgumentsResponse(res, statusCode, error.details);
} else {
this.invalidArgumentsResponse(res, statusCode, error.message);
}
}
}

Expand Down

0 comments on commit 16f4622

Please sign in to comment.