egg
egg copied to clipboard
Common egg Error Codes
前置资料
- 参考 Node.js Error Codes: https://npm.taobao.org/mirrors/node/latest/docs/api/errors.html#errors_node_js_error_codes
- 所有由 egg 和 egg 插件引起已知的 Error 异常,都需要规范 err.code
RFC:How to create an Error
Usage
- built-in Error
const errors = require('egg').errors;
const err = new errors.TypeError('ERR_EGG_SOME_ERROR_CODE_STRING', 'Some error haha');
console.log(err.code); // 'ERR_EGG_SOME_ERROR_CODE_STRING'
- custom Error
const errors = require('egg').errors;
// register a new subclass of TypeError with code 'ERR_EGG_MY_ERROR'
// if code 'ERR_EGG_MY_ERROR' exists, then will throw a TypeError with code 'ERR_EGG_DUPLICATE_CODE'
errors.E('ERR_EGG_MY_ERROR', TypeError);
const err = new errors.ERR_EGG_MY_ERROR('my error here');
console.log(err.name); // 'TypeError'
console.log(err.code); // 'ERR_EGG_MY_ERROR'
message
and code
An error should contains two message
and code
properties by default.
message
maybe change cause by typo, but it won't cause major
change, it juest patch
or minor
change.
code
should keep stable after it first come out.
cc @dead-horse @popomore
看要不要起个 RFC
@okoala 就遵循 node 的实现方式和规范来吧
https://github.com/nodejs/node/blob/master/lib/internal/errors.js#L100
example: https://github.com/nodejs/node/blob/4d89e3c261ebd67baf4ac3d17033419e1b3075f2/lib/internal/url.js#L827
if (typeof method !== 'function') {
throw new errors.TypeError('ERR_ARG_NOT_ITERABLE', 'Query pairs');
}
👍
需要考虑插件和上层框架注册 error code 到全局的机制。
用途:
- 规范化错误名
- 报错提示可以 i18n
- 便于开发者 google 检索报错
- 可以提供类似 angular 这样的指引: https://docs.angularjs.org/error/$compile/baddir,即 error 输出简单的提示,并输出一条链接,开发者点击后可以访问官网看详细的指引。
https://github.com/nodejs/node/blob/master/doc/guides/using-internal-errors.md
没有暴露出来,得 egg 自行实现了
对一些业务场景错误状态是否也会提供支持?
@okoala 业务场景就是由bu框架或者应用自身自己去按这个规范定义了,使用方式是一样的。
这感觉还是整理一个错误码最佳实践让开发参考吧
@jtyjty99999 对,我是这个意思~
业务的错误码需求和框架的错误码需求不一样,这个只用考虑框架的就可以了。
https://github.com/eggjs/egg/issues/1047#issue-235462770 补充来 RFC 说明,egg 默认提供一个 errors
帮助类,快速自定义自己的异常。
@atian25 i18n 还是在应用展示层考虑吧,不在框架层做。
https://github.com/eggjs/egg-errors
@popomore ts ?
ref https://github.com/eggjs/egg/issues/1086