抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

Mr.wang

Time flies and people come and go

记录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
//  middlewares\exception.js
class HttpException extends Error {
constructor(msg = '服务器错误', errorCode = 10000, code = 400) {
super()
this.errorCode = errorCode
this.code = code
this.msg = msg
}
}
//const { HttpException } = require('../core/http-exception')
// 统一处理异常中间件
const catchError = async (ctx, next) => {
try {
await next()
} catch (error) {
// 不是 HttpException 的情况下且在开发环境,错误抛出
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)

评论