From a77e02aee107996b99b9fc8d0295e47c4a7140b4 Mon Sep 17 00:00:00 2001 From: SongWuKong Date: Fri, 17 Jun 2022 23:28:31 +0800 Subject: [PATCH] feat: add responseError for interceptor (#15) * feat: add responseError for interceptor * add await --- lib/service/CoaApplication.ts | 17 ++++++++++++----- lib/service/CoaInterceptor.ts | 3 +++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/service/CoaApplication.ts b/lib/service/CoaApplication.ts index 0c7beb8..86c6072 100644 --- a/lib/service/CoaApplication.ts +++ b/lib/service/CoaApplication.ts @@ -73,14 +73,21 @@ export class CoaApplication { // 判断是否打印错误 if (!(isCoaError || isCoaContextError) || e.stdout !== false) echo.error(e.stack || e.toString() || e) - const error = { - code: (isCoaError && e.code) || (isCoaContextError && 'Context.Error.' + _.toString(e.code)) || 'Gateway.HandlerError', - message: e.message || e.toString(), + // 默认错误处理 + const handlerError = { + error: { + code: (isCoaError && e.code) || (isCoaContextError && 'Context.Error.' + _.toString(e.code)) || 'Gateway.HandlerError', + message: e.message || e.toString(), + }, } - ctx.json({ error }) + // 错误拦截器 + const interceptorError = await this.interceptor?.responseError(handlerError, e) + // 得到最终结果 + const error = interceptorError || handlerError + ctx.json(error) echo.warn('# 请求: %s %s %j', ctx.req.method, ctx.req.url, ctx.request.body) - echo.warn('# 返回: %j', { error }) + echo.warn('# 返回: %j', error) } // 如果不处理,则直接返回结果 diff --git a/lib/service/CoaInterceptor.ts b/lib/service/CoaInterceptor.ts index a147788..b35191c 100644 --- a/lib/service/CoaInterceptor.ts +++ b/lib/service/CoaInterceptor.ts @@ -7,4 +7,7 @@ export class CoaInterceptor { // eslint-disable-next-line @typescript-eslint/no-unused-vars async response(ctx: CoaContext, result: CoaRouterHandlerResult): Promise {} + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async responseError(handlerError: { error: { code: string; message: string } }, rawError: any): Promise {} }