- 在根目录下创建middleWares文件夹,存放自定义中间件
- 在middleWares目录下创建exception.js异常处理中间件,来捕获异常
const {HttpException} = require('../core/http-exception')
const catchError = async (ctx, next)=>{
try {
await next()
} catch (error) {
if(error instanceof HttpException){
ctx.body = {
msg: error.msg,
error_code: error.errorCode,
requestUrl: `${ctx.method} ${ctx.path}`
}
ctx.status = error.code
} else {
// 未知异常处理
ctx.body = {
msg: 'we made a mistake',
error_code: 999,
requestUrl: `${ctx.method} ${ctx.path}`
}
ctx.status = 5000
}
}
}
module.exports = catchError
- 在app.js中注册异常中间件
const catchError = require('./middleWares/exception')
app.use(catchError)
- 在core文件夹下创建http异常处理逻辑文件http-exception.js
class HttpException extends Error{
constructor(msg="服务器异常", errorCode=10000, code=400){
super()
this.errorCode = errorCode
this.code = code
this.msg = msg
}
}
class ParameterException extends HttpException{
constructor(msg="参数错误", errorCode="10000"){
super()
this.code = 400
this.msg = msg
this.errorCode = errorCode
}
}
module.exports = {
HttpException,
ParameterException
}
- 在路由中间中使用异常处理
calssic.js
const Router = require('koa-router')
const { ParameterException } = require('../../../core/http-exception')
const router = new Router()
router.post('/v1/:id/classic/latest', (ctx, next)=>{
const param = ctx.params
const query = ctx.request.query
const header = ctx.request.header
const body = ctx.request.body
if(true){
const error = new ParameterException()
throw error
}
ctx.body = {
param,
query,
header,
body
}
})
module.exports = router
- 在postman中发送请求