Files
errorx/example/imports/readme.md
T
yun 21293673e1 refactor!: 错误值改为不可变,修复并发崩溃与兜底缺陷
BREAKING CHANGE: 相对 v0.0.1 的 API 变更
- 删除全部 Set* 方法,改为返回新值的 With*;错误值不可变,包级常量可并发使用
- 错误值不再持有 context,只保存语言标识(WithLang),渲染时再传 ctx
- 删除兼容别名 Errf / ErrfKV / Msgf / NewLanguage / NewStruct 与空操作 Copy()
- Msgf 改为 MsgWith,NewErrorf 改为 NewErrorWith;ErrorLanguage 不再实现 ErrorInterface

修复
- Copy 浅拷贝共享 format map,并发下 fatal error: concurrent map writes
- 包级常量被 Set* 污染,请求之间互相改写错误文案
- langx.RegisterCode / RegisterTrans 覆盖注册表后,运行时错误码退化为默认码、文案退化为裸 key
- 未注册 key 静默返回默认码 + 裸 key,现返回 500 + 未注册提示
- NewError(nil, ...) 与非 string 的 Accept-Language 触发 panic

新增
- Wrap / Unwrap / errors.Is 按 key 匹配、调用栈(惰性解析)、%+v 输出 cause 与栈
- 错误常量自带默认文案兜底 + errorx 侧常量注册表(不依赖 langx 可变状态)
- 根 README、3 个可运行示例、17 个断言测试(语句覆盖率 97.2%)、基准测试

依赖
- github.com/yuninks/langx v0.0.7 -> v0.1.0
2026-09-21 00:43:43 +08:00

31 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# langx 资源加载示例
本目录演示 langx 的三种资源加载方式,以及它们与 errorx 的配合。
| 方式 | 函数 | 语义 |
| --- | --- | --- |
| 追加 | `langx.AppendCode` / `langx.AppendTrans` | 按键合并,**业务代码推荐** |
| 打包 | `langx.RegisterEmbed(fs)` | 按键合并,用 //go:embed 把 lang 目录打进二进制,随程序发布 |
| 目录 | `langx.RegisterDir(dir)` | 按键合并,运行时读目录,改文案不用重新编译 |
## 资源文件格式
- `code.json`:`{"key": 业务码}`
- `zh.json` / `en.json`:`{"key": "文案 #占位符#"}`
- 子目录的第一段是语言名:`zh/common.json`、`zh/errors.json` 都会并入 `zh`
## 注意两种注册语义(langx v0.1.0 起)
- `RegisterCode` / `RegisterTrans`:**整体替换**对应的注册表,会冲掉 `errorx.New` 在 init 阶段追加的内置文案;
- `RegisterEmbed` / `RegisterDir` / `RegisterFS`:**按键合并**,不影响已经注册的资源。
即使被整体替换,errorx 的错误常量自带 code 与默认文案,查不到时会自动回填,
所以 `errorx.Error.Err().GetCode()` 永远是 400、文案永远可读,不会退化成裸 key。
但如果直接用 `langx.GetTransFormat` 读这些 key,就会看到裸 key。
运行:
```bash
go run ./example/imports
```