|
7 | 7 |
|
8 | 8 | # errors |
9 | 9 |
|
10 | | -Stdlib `errors` package extension. `go1.13` `errors.Is` and `errors.As` are the same functions as in stdlib (not even copies). |
| 10 | +`errors` is a wrapper around the standard `errors.New` and `fmt.Errorf` functions. |
| 11 | +It unifies their APIs, allowing you to create new errors or wrap existing ones with rich context (formatted message with arguments). |
11 | 12 |
|
12 | | -```go |
13 | | -// as usual |
14 | | -err = errors.New("msg") |
| 13 | +It provides two core functions: |
15 | 14 |
|
16 | | -// do not capture caller info |
17 | | -err = errors.NewNoLoc("msg") |
18 | | - |
19 | | -// fmt.Sprintf like |
20 | | -err = errors.New("message %v", "args") |
21 | | - |
22 | | -// one Frame higher |
23 | | -err = errors.NewDepth(1, "msg") |
24 | | - |
25 | | -// the same result as previous |
26 | | -pc := loc.Caller(1) |
27 | | -err = errors.NewLoc(pc, "msg") |
28 | | - |
29 | | -// Wrap error |
30 | | -err = errors.Wrap(err, "msg %v", "args") |
31 | | - |
32 | | -// all the same function types are available |
33 | | -err = errors.WrapNoLoc(err, "msg") |
34 | | - |
35 | | -err = errors.WrapDepth(err, 1, "msg %v", "args") |
36 | | - |
37 | | -err = errors.WrapLoc(err, pc, "msg %v", "args") |
38 | 15 | ``` |
39 | | - |
40 | | -## Caller |
41 | | - |
42 | | -Caller frame can be added to error so later you can get to know where error was generated. It's added by default and captures instruction calling `errors.(Wrap|New)*`. |
43 | | - |
44 | | -Caller is moved to a separate module [tlog.app/go/loc](https://github.com/tlog-dev/loc). |
45 | | - |
46 | | -```go |
47 | | -pc := loc.Caller(1) |
48 | | - |
49 | | -pc = loc.FuncEntry(1) |
| 16 | +errors.New(format string, args ...any) error |
| 17 | +errors.Wrap(err error, format string, args ...any) error |
50 | 18 | ``` |
| 19 | + |
| 20 | +While it previously had more features, I eventually realized that, |
| 21 | +in most cases, anything beyond simple error wrapping is an overcomplication. |
0 commit comments