记录node-koa2服务器开发中好用的方法和技巧
全局处理函数异常
使用中间件对于抛出异常的处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class HttpException extends Error { constructor(msg = '服务器错误', errorCode = 10000, code = 400) { super() this.errorCode = errorCode this.code = code this.msg = msg } }
const catchError = async (ctx, next) => { try { await next() } catch (error) { const isHttpException = error instanceof HttpException const isDev = global.config.environment === 'dev' if (isDev && !isHttpException) { throw error } if (isHttpException) { ctx.body = { msg: error.msg, error_code: error.errorCode, request: `${ctx.method} ${ctx.path}`, } ctx.status = error.code } else { ctx.body = { msg: '抱歉,未知的错误', error_code: 999, request: `${ctx.method} ${ctx.path}`, } ctx.status = 500 } } } module.exports = catchError
|
中间件注册app.js
1 2 3 4 5 6
| const Koa = require('koa') const catchError = require('./middlewares/exception') const app = new Koa()
app.use(catchError) app.listen(10086)
|