💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ### Koa2 异常处理 * [ ] 自定义异常 ![](https://box.kancloud.cn/be5655c81c13da9d8db0885d06cb9165_300x294.png) >[danger] 定义一个全局异常处理类 http-exceptions.js ~~~ // 自定义异常 class HttpExceptions extends Error { constructor(msg='服务器异常', errorCode = 0, code = 400) { super() this.msg = msg this.errorCode = errorCode this.code = code } } // 资源未找到异常 class ResourceErr extends HttpExceptions { constructor(msg='资源未找到', errorCode = 1, code = 404) { super(msg, errorCode, code) } } module.exports = { HttpExceptions, ResourceErr } ~~~ ***** * [ ] 定义一个全局捕获异常中间件 ![](https://box.kancloud.cn/22de4dcf2ee6532f48ca32865028bdd0_268x265.png) ~~~ const { HttpExceptions } = require('../core/http-exceptions') // 全局异常捕捉中间件 const Exception = async (ctx, next) => { try { await next() } catch(error) { const { msg, errorCode, code } = error const url = `${ctx.method} : ${ctx.request.path}` if (error instanceof HttpExceptions) { // 已知异常 ctx.body = { msg, errorCode, url } ctx.status = code } else { // 未知异常 ctx.body = { msg: '服务器内部错误~', errorCode: 999, url } ctx.status = 500 } } } module.exports = Exception ~~~ ***** * [ ] 使用 ~~~ const Router = require('koa-router') const router = new Router() const { ResourceErr } = require('../../../core/http-exceptions') router.get('/api/v1/news/:id', (ctx, next) => { // 自定义异常 throw new ResourceErr() }) module.exports = router ~~~