diff --git a/src/server.ts b/src/server.ts index 5eeaabc..bab555b 100644 --- a/src/server.ts +++ b/src/server.ts @@ -2,8 +2,10 @@ import Koa from "koa"; import router from "./routers/router"; import bodyParser from "koa-bodyparser"; import InitHandler from "./routers/handler"; +import catchError from "./utils/catchError"; // 使用路由 const app = new Koa(); +app.use(catchError); app.use(bodyParser()); diff --git a/src/utils/catchError.ts b/src/utils/catchError.ts new file mode 100644 index 0000000..40ca92c --- /dev/null +++ b/src/utils/catchError.ts @@ -0,0 +1,12 @@ + +const catchError = async (ctx: any, next: any) => { + try { + await next(); + } catch (error:any) { + if (error.errorCode) { + console.log("捕获到异常") + return ctx.body = error.toString(); + } + } +} +export default catchError; \ No newline at end of file