You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`go-xerrors` is a simple, idiomatic, lightweight Go package that provides utilities for error handling. It offers functions and types to support stack traces, multi-errors, and simplified panic handling. The package is compatible with Go's standard error handling mechanisms, such as `errors.As`, `errors.Is`, and `errors.Unwrap`, including features from Go 1.13 and 1.20.
4
6
5
7
**Main Features:**
@@ -20,6 +22,49 @@ go get -u github.com/mdobak/go-xerrors
20
22
21
23
## Usage
22
24
25
+
### Example
26
+
27
+
The following example demonstrates the basic usage of `go-xerrors` for creating and handling errors.
28
+
29
+
```go
30
+
package main
31
+
32
+
import (
33
+
"database/sql"
34
+
"fmt"
35
+
36
+
"github.com/mdobak/go-xerrors"
37
+
)
38
+
39
+
funcfindUserByID(idint) error {
40
+
// Simulate a standard library error.
41
+
err:= sql.ErrNoRows
42
+
43
+
// Wrap the original error with additional context and capture a stack trace
44
+
// at this point in the call stack.
45
+
return xerrors.Newf("user %d not found: %w", id, err)
46
+
}
47
+
48
+
funcmain() {
49
+
err:=findUserByID(123)
50
+
if err != nil {
51
+
// 1. The standard Error() method provides a concise, log-friendly message.
52
+
fmt.Println("Concise log message:", err.Error())
53
+
// Output: user 123 not found: sql: no rows in result set
54
+
55
+
// 2. xerrors.Print provides a rich, multi-line report for developers,
56
+
// including the stack trace from where the error was wrapped.
57
+
xerrors.Print(err)
58
+
// Output:
59
+
// Error: user 123 not found: sql: no rows in result set
60
+
// at main.findUserByID (/home/user/app/main.go:15)
61
+
// at main.main (/home/user/app/main.go:20)
62
+
// at runtime.main (/usr/local/go/src/runtime/proc.go:250)
63
+
// at runtime.goexit (/usr/local/go/src/runtime/asm_amd64.s:1594)
64
+
}
65
+
}
66
+
```
67
+
23
68
### Creating Errors with Stack Traces
24
69
25
70
The primary way to create an error in `go-xerrors` is by using the `xerrors.New` or `xerrors.Newf` functions:
@@ -53,7 +98,7 @@ Error: something went wrong
53
98
54
99
### Working with Stack Traces
55
100
56
-
To retrieve only the stack trace information programmatically:
101
+
To retrieve the stack trace information programmatically:
57
102
58
103
```go
59
104
trace:= xerrors.StackTrace(err)
@@ -95,7 +140,7 @@ if err != nil {
95
140
}
96
141
```
97
142
98
-
Note that wrapping multiple errors with `xerrors.Newf` is possible on Go 1.20 and later.
143
+
Note that wrapping multiple errors with `xerrors.Newf` is possible only in Go 1.20 and later.
Note that wrapping multiple errors with `xerrors.Joinf` is possible on Go 1.20 and later.
159
+
Note that wrapping multiple errors with `xerrors.Joinf` is possible only in Go 1.20 and later.
115
160
116
161
The main difference between Go's `fmt.Errorf` and `xerrors.Newf`/`xerrors.Joinf` is that the latter functions preserve the error chain, whereas `fmt.Errorf` flattens it (i.e., its `Unwrap` method returns all underlying errors at once instead of just the next one in the chain).
117
162
118
163
### Sentinel Errors
119
164
120
-
Sentinel errors are predefinederror values representing specific, known failure conditions. `go-xerrors` provides `xerrors.Message` to create distinct sentinel error values:
165
+
Sentinel errors are predefined, exported error values used to signal specific, well-known conditions (e.g., `io.EOF`). The `go-xerrors`package provides the `xerrors.Message` and `xerrors.Messagef` functions to create distinct sentinel error values:
The resulting multi-error implements the standard `error` interface as well as `errors.Is`, `errors.As`, and `errors.Unwrap`, allowing you to check for specific errors or extract them.
178
223
179
224
**Comparison with Go 1.20 `errors.Join`:**
180
225
181
-
Go 1.20 introduced `errors.Join` for error aggregation. While serving a similar purpose, `xerrors.Append` offers:
182
-
183
-
1.**Individual Stack Traces**: Preserves the individual stack traces associated with each appended error
184
-
2.**Enhanced Formatting**: Provides detailed, structured output for multi-errors
185
-
3.**Consistent `Error()` Output**: Produces a concise, single-line summary
226
+
Go 1.20 introduced `errors.Join` for error aggregation. While it serves a similar purpose, `xerrors.Append` preserves the individual stack traces associated with each appended error and adheres to the convention of returning a single line from the `Error()` method.
186
227
187
228
### Simplified Panic Handling
188
229
230
+
Panics can be challenging to locate and handle effectively in Go applications, especially when using `recover()`. Common issues, such as nil pointer dereferences or out-of-bounds slice accesses, often result in unclear panic messages. Without a stack trace, pinpointing the origin of the panic can be difficult.
231
+
189
232
`go-xerrors` provides utilities to convert panic values into proper errors with stack traces.
The returned error implements the `PanicError` interface, which provides access to the original panic value via the `Panic()` method.
223
266
224
-
### When to use `New`, `Join`, or`Append`
267
+
### Choosing Between `New`, `Join`, and`Append`
225
268
226
-
While all three functions can be used to aggregate errors, they serve different purposes:
269
+
While these functions can all be used to aggregate errors, they each serve distinct purposes:
227
270
228
-
-**`xerrors.New`**: Create errors with stack traces, useful for wrapping existing errors to add context
229
-
-**`xerrors.Join`**: Create chained errors without stack traces, useful for defining sentinel errors
230
-
-**`xerrors.Append`**: Create multi-errors by aggregating independent errors
271
+
-**`xerrors.New`**: Use this to create errors and attach stack traces, especially when wrapping existing errors to provide additional context.
272
+
-**`xerrors.Join`**: Use this to chain errors together _without_ capturing stack traces. This is most appropriate for creating sentinel errors.
273
+
-**`xerrors.Append`**: Use this to aggregate multiple, independent errors into a single multi-error. This is useful when several operations might fail, and you want to report all failures at once.
0 commit comments