Skip to content

Commit

Permalink
feat: add error catch middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
ruiming committed Mar 11, 2018
1 parent 66e8e3d commit 0875010
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"private": true,
"scripts": {
"start": "node ./build/index.js",
"dev": "nodemon --exec ./node_modules/.bin/ts-node -- ./src/index.ts",
"dev": "nodemon --ignore doc.json --exec ./node_modules/.bin/ts-node -- ./src/index.ts",
"build": "tsc",
"test:run": "./node_modules/.bin/mocha --require espower-typescript/guess 'test/**/*.ts' --timeout=10000",
"test:coverage": "nyc npm run test:run",
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Database from './libraries/Database';
import Cache from './libraries/Cache';
import docGenerator from 'routing-controllers-openapi-v3';
import { IDefaultSuccessResponse } from './interfaces/Helper';
import errorCatch from './middlewares/errorCatch';

const { port } = config;

Expand All @@ -19,10 +20,10 @@ useContainerForOrm(Container);
const app = new Koa();

app.use(logger());
app.use(errorCatch());

useKoaServer(app, {
cors: true,
routePrefix: '/',
controllers: [`${__dirname}/controllers/*.{js,ts}`],
defaultErrorHandler: true
});
Expand Down
30 changes: 30 additions & 0 deletions src/middlewares/errorCatch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { ValidationError } from 'class-validator';
import { Context } from 'koa';
import { BadRequestError, InternalServerError } from 'routing-controllers';

export default function errorCatch(): (ctx: Context, next: () => Promise<{}>) => Promise<void> {
return async (ctx: Context, next: () => Promise<{}>) => {
try {
await next();
} catch (e) {
let message;
if (Reflect.has(e, 'errors') && e.errors[0] instanceof ValidationError) {
message = Object.values(e.errors[0].constraints).join(';');
e.status = 400;
} else if (e instanceof BadRequestError) {
// console.log('『捕获 BadRequestError 』\n', e)
} else if (e instanceof InternalServerError) {
console.error('『捕获 InternalServerError 』\n', e);
} else if (e.httpCode === 401 || e.status === 401) {
message = e.message;
} else {
console.error('『程序异常 o(╥﹏╥)o』\n', e);
e.message = '程序异常';
}
ctx.status = e.httpCode || e.status || 500;
ctx.body = {
message: message || e.message
};
}
};
}

0 comments on commit 0875010

Please sign in to comment.