egg-onerror
egg-onerror copied to clipboard
feat: add biz handler
There is three case:
- If it's an egg error, it will format response
- If it's an egg exception, it will format response and log an error
- if it's a normal error, it will be throw that catched by onerror handler
Checklist
- [ ]
npm testpasses - [ ] tests and/or benchmarks are included
- [ ] documentation is changed or added
- [ ] commit message follows commit guidelines
Affected core subsystem(s)
Description of change
先看看处理是否合适。
非 json 的没想好怎么处理,内容协商 egg 做的不是很好。
@popomore 非 json 的本来 koa-onerror 就已经处理的了,得复用起来。
这是是在前面拦截统一处理的,onerror 就是未捕获异常的处理,所以我觉得业务异常都可以在这里提供处理的扩张。
是不是提供这样的配置,让开发者明确是处理哪种类型,格式化统一只给一个 error 对象。
onerror.uncaught.formatJSON onerror.biz.formatJSON onerror.uncaught.formatText onerror.biz.formatText
Codecov Report
Merging #29 into master will increase coverage by
0.54%. The diff coverage is98%.
@@ Coverage Diff @@
## master #29 +/- ##
==========================================
+ Coverage 96.98% 97.53% +0.54%
==========================================
Files 5 6 +1
Lines 166 203 +37
==========================================
+ Hits 161 198 +37
Misses 5 5
| Impacted Files | Coverage Δ | |
|---|---|---|
| config/config.default.js | 100% <ø> (ø) |
:arrow_up: |
| agent.js | 100% <100%> (ø) |
:arrow_up: |
| app/middleware/egg_onerror_handler.js | 100% <100%> (ø) |
|
| app.js | 97.22% <96.87%> (+0.16%) |
:arrow_up: |
Continue to review full report at Codecov.
Legend - Click here to learn more
Δ = absolute <relative> (impact),ø = not affected,? = missing dataPowered by Codecov. Last update 4824a04...8e18cfb. Read the comment docs.
代码又改了下
看看系统的是否也要加,因为这个是兜底的,如果出现了异常就会真挂掉。
还有一个纠结点是业务处理现在是无法处理默认的 Error 的,如果不提供系统的 format,那这个 error 处理只能使用 onerror 默认的了。
应用也可以将默认的 Error 处理了。按道理应用只处理自己的异常。
@popomore 清晰多了,先将文档写出来,文档里面将3种场景都写出示例代码,从开发者角度看看整个过程是否合理。
这个放在 onerror 插件里面给我的感觉还是有点奇怪,因为里面内嵌了一些 egg-errors 的逻辑,需要配套使用。我觉得还不如单独实现一个 egg-biz-error 的插件,统一提供 egg-errors 和对应的中间件处理,给用户的感知是统一的。
例如在这里配置 application.formatXX 方法, 但是一些 builtin 的异常又没有按照这个格式来处理,会让人有点疑惑。
如果是新增一个 egg-biz-error 插件,所有通过插件提供的方式抛出的异常都会被这个插件处理,系统 builtin 异常不会处理,就比较合理。
egg-biz-error 插件如果接口稳定的话,也可以在 egg 中默认开启
我先把文档写一下,这样比较容易理解。
egg-errors 单独使用是为了让库、插件、框架、应用都可以单独依赖来使用,而不是依赖一个 egg-biz-error 的插件。
抽出 biz-error 插件做这个错误处理我觉得也没有问题,但是这个属于 egg 错误处理的核心功能,所以我觉得再抽个插件比较麻烦。
例如在这里配置 application.formatXX 方法, 但是一些 builtin 的异常又没有按照这个格式来处理,会让人有点疑惑。
这个我是这样想的,builtin 异常可能出现在一些依赖库里,业务需要对其做处理,如果不做处理就认为是未捕获异常。
try {
// 调用依赖库
} catch (err) {
throw MyException.from(err);
}
link 下 RFC 或文档,从使用者角度来看下,可能会更容易理解下。
我理解 egg-errors 作为单独库的的目的,我的意思是如果确定下来,可以直接将 egg-errors 从 egg-core 开始内置,这样在 egg-onerror 插件里面处理 egg-errors 相关的东西就合适了。
不是内置,是希望所有的错误都用这种方式封装。
我们是不是需要提供默认项,如果开启了 errorHandler 而使用默认值的时候会跟原来 onerror 的默认处理有差异。