koa中異常處理

  1. 在根目錄下創建middleWares文件夾,存放自定義中間件
  2. 在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
  1. 在app.js中註冊異常中間件
const catchError = require('./middleWares/exception')
app.use(catchError)
  1. 在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
}
  1. 在路由中間中使用異常處理
    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
  1. 在postman中發送請求
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章