Skip to content

Commit

Permalink
feat: add responseError for interceptor (#15)
Browse files Browse the repository at this point in the history
* feat: add responseError for interceptor

* add await
  • Loading branch information
imswk authored Jun 17, 2022
1 parent 5ed0f04 commit a77e02a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
17 changes: 12 additions & 5 deletions lib/service/CoaApplication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,21 @@ export class CoaApplication<T extends CoaContext> {
// 判断是否打印错误
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)
}

// 如果不处理,则直接返回结果
Expand Down
3 changes: 3 additions & 0 deletions lib/service/CoaInterceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,7 @@ export class CoaInterceptor {

// eslint-disable-next-line @typescript-eslint/no-unused-vars
async response(ctx: CoaContext, result: CoaRouterHandlerResult): Promise<CoaRouterHandlerResult | void> {}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
async responseError(handlerError: { error: { code: string; message: string } }, rawError: any): Promise<CoaRouterHandlerResult | void> {}
}

0 comments on commit a77e02a

Please sign in to comment.