Skip to content

Commit a77e02a

Browse files
authored
feat: add responseError for interceptor (#15)
* feat: add responseError for interceptor * add await
1 parent 5ed0f04 commit a77e02a

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

lib/service/CoaApplication.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,21 @@ export class CoaApplication<T extends CoaContext> {
7373
// 判断是否打印错误
7474
if (!(isCoaError || isCoaContextError) || e.stdout !== false) echo.error(e.stack || e.toString() || e)
7575

76-
const error = {
77-
code: (isCoaError && e.code) || (isCoaContextError && 'Context.Error.' + _.toString(e.code)) || 'Gateway.HandlerError',
78-
message: e.message || e.toString(),
76+
// 默认错误处理
77+
const handlerError = {
78+
error: {
79+
code: (isCoaError && e.code) || (isCoaContextError && 'Context.Error.' + _.toString(e.code)) || 'Gateway.HandlerError',
80+
message: e.message || e.toString(),
81+
},
7982
}
80-
ctx.json({ error })
83+
// 错误拦截器
84+
const interceptorError = await this.interceptor?.responseError(handlerError, e)
85+
// 得到最终结果
86+
const error = interceptorError || handlerError
87+
ctx.json(error)
8188

8289
echo.warn('# 请求: %s %s %j', ctx.req.method, ctx.req.url, ctx.request.body)
83-
echo.warn('# 返回: %j', { error })
90+
echo.warn('# 返回: %j', error)
8491
}
8592

8693
// 如果不处理,则直接返回结果

lib/service/CoaInterceptor.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,7 @@ export class CoaInterceptor {
77

88
// eslint-disable-next-line @typescript-eslint/no-unused-vars
99
async response(ctx: CoaContext, result: CoaRouterHandlerResult): Promise<CoaRouterHandlerResult | void> {}
10+
11+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
12+
async responseError(handlerError: { error: { code: string; message: string } }, rawError: any): Promise<CoaRouterHandlerResult | void> {}
1013
}

0 commit comments

Comments
 (0)