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.
5
+
`go-xerrors` is a small, idiomatic library that makes error handling in Go easier. It provides utilities for creating errorswith stack traces, wrapping existing errors, aggregating multiple errors, and recovering from panics.
6
6
7
-
**Main Features:**
7
+
**Main features**
8
8
9
-
-**Stack Traces**: Captures stack traces when creating errors to help locate the origin of issues during debugging
10
-
-**Multi-Errors**: Aggregates multiple errors into a single error instance while maintaining individual error context
11
-
-**Error Wrapping**: Wraps errors with additional context while preserving compatibility with `errors.Is`, `errors.As`, and `errors.Unwrap`
12
-
-**Panic Handling**: Converts panic values to standard Go errors with stack traces for structured error recovery
13
-
-**Zero Dependencies**: Implements error handling utilities with no external dependencies beyond the Go standard library
9
+
-**Stack traces**: Capture stack traces when creating errors to pinpoint the source during debugging.
10
+
-**Multi-errors**: Aggregate multiple errors into a single error while preserving individual context.
11
+
-**Panic handling**: Convert panic values to standard Go errors with stack traces.
12
+
-**Zero dependencies**: No external dependencies beyond the Go standard library.
14
13
15
-
> **Note:** This package is considered stable and will therefore be rarely updated, mostly for bug fixes and adding support for new Go versions and features. With the release of version 1.0, the API is frozen, and no breaking changes will be introduced in future releases.
14
+
> Note: This package is stable. Updates are rare and limited to bug fixes and support for new Go versions or error-related features. Since 1.0, the API has been frozen. No breaking changes will be introduced in future releases.
16
15
17
16
---
18
17
@@ -26,7 +25,7 @@ go get -u github.com/mdobak/go-xerrors
26
25
27
26
### Example
28
27
29
-
The following example demonstrates the basic usage of `go-xerrors` for creating and handling errors.
28
+
Here’s a quick example of creating and handling errors with `go-xerrors`.
// 1. The standard Error() method provides a concise, log-friendly message.
54
-
fmt.Println("Concise log message:", err.Error())
55
-
// Output: user 123 not found: sql: no rows in result set
52
+
// 1) err.Error() returns a concise, log-friendly message.
53
+
fmt.Println(err.Error())
54
+
// Output:
55
+
// user 123 not found: sql: no rows in result set
56
56
57
-
// 2. xerrors.Print provides a rich, multi-line report for developers,
58
-
// including the stack trace from where the error was wrapped.
57
+
// 2) xerrors.Print shows a detailed message with a stack trace.
59
58
xerrors.Print(err)
60
59
// Output:
61
60
// Error: user 123 not found: sql: no rows in result set
@@ -72,18 +71,18 @@ func main() {
72
71
The primary way to create an error in `go-xerrors` is by using the `xerrors.New` or `xerrors.Newf` functions:
73
72
74
73
```go
75
-
// Create a new error with a stack trace
74
+
// Create a new error with a stack trace.
76
75
err:= xerrors.New("something went wrong")
77
76
78
-
// Create a formatted error with a stack trace
77
+
// Create a formatted error with a stack trace.
79
78
err:= xerrors.Newf("something went wrong: %s", reason)
80
79
```
81
80
82
-
Calling the standard `Error()`method on `err`returns only the message ("something went wrong"), adhering to the Go convention of providing a concise error description.
81
+
Calling `err.Error()` returns only the message ("something went wrong"), following the Go convention of keeping error strings concise.
83
82
84
83
### Displaying Detailed Errors
85
84
86
-
To display the error with the associated stack trace and additional details, use the `xerrors.Print`, `xerrors.Sprint`, or `xerrors.Fprint` functions:
85
+
To print the error with its stack trace and details, use `xerrors.Print`, `xerrors.Sprint`, or `xerrors.Fprint`:
87
86
88
87
```go
89
88
xerrors.Print(err)
@@ -115,16 +114,17 @@ at testing.tRunner (/home/user/go/src/testing/testing.go:1259)
115
114
at runtime.goexit (/home/user/go/src/runtime/asm_arm64.s:1133)
116
115
```
117
116
118
-
You can also explicitly add a stack trace to an existing error:
117
+
You can also add a stack trace to an existing error with `xerrors.WithStackTrace`, and choose how many frames to skip. This is handy when a helper creates errors but you don’t want its own frame captured:
119
118
120
119
```go
121
-
err:=someFunction()
122
-
errWithStack:= xerrors.WithStackTrace(err, 0) // 0 skips no frames
120
+
funcerrNotFound(pathstring) error {
121
+
return xerrors.WithStackTrace(ErrNotFound{path: path}, 1) // skip one frame
122
+
}
123
123
```
124
124
125
125
### Wrapping Errors
126
126
127
-
The `xerrors.New` and `xerrors.Newf` functions can also wrap existing errors:
127
+
You can also wrap existing errors:
128
128
129
129
```go
130
130
output, err:= json.Marshal(data)
@@ -142,11 +142,11 @@ if err != nil {
142
142
}
143
143
```
144
144
145
-
Note that wrapping multiple errors with `xerrors.Newf` is possible only in Go 1.20 and later.
145
+
> Wrapping multiple errors with `xerrors.Newf` is possible only in Go 1.20 and later.
146
146
147
147
### Creating Error Chains Without Stack Traces
148
148
149
-
For situations where you don't need a stack trace (such as creating sentinel errors), use `xerrors.Join` and `xerrors.Joinf`:
149
+
When you don’t need a stack trace (for example, when creating sentinel errors), use `xerrors.Join` and `xerrors.Joinf`:
Note that wrapping multiple errors with `xerrors.Joinf` is possible only in Go 1.20 and later.
161
+
> Wrapping multiple errors with `xerrors.Joinf` is possible only in Go 1.20 and later.
162
162
163
163
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).
164
164
@@ -206,18 +206,24 @@ if len(input.Password) < 8 {
206
206
}
207
207
208
208
if err != nil {
209
-
fmt.Println(err.Error()) // [username cannot be empty, password must be at least 8 characters]
209
+
fmt.Println(err.Error())
210
+
// Output:
211
+
// [username cannot be empty, password must be at least 8 characters]
210
212
211
213
// Detailed output using xerrors.Print:
212
214
xerrors.Print(err)
213
215
// Output:
214
216
// Error: [username cannot be empty, password must be at least 8 characters]
215
217
// 1. Error: username cannot be empty
216
-
// at main.validateInput (/path/to/your/file.go:XX)
217
-
// ... stack trace ...
218
+
// at main.validateInput (/home/user/app/main.go:40)
219
+
// at main.main (/home/user/app/main.go:20)
220
+
// at runtime.main (/usr/local/go/src/runtime/proc.go:250)
221
+
// at runtime.goexit (/usr/local/go/src/runtime/asm_amd64.s:1594)
218
222
// 2. Error: password must be at least 8 characters
219
-
// at main.validateInput (/path/to/your/file.go:YY)
220
-
// ... stack trace ...
223
+
// at main.validateInput (/home/user/app/main.go:43)
224
+
// at main.main (/home/user/app/main.go:20)
225
+
// at runtime.main (/usr/local/go/src/runtime/proc.go:250)
226
+
// at runtime.goexit (/usr/local/go/src/runtime/asm_amd64.s:1594)
221
227
}
222
228
```
223
229
@@ -271,7 +277,7 @@ The returned error implements the `PanicError` interface, which provides access
271
277
While these functions can all be used to aggregate errors, they each serve distinct purposes:
272
278
273
279
-**`xerrors.New`**: Use this to create errors and attach stack traces, especially when wrapping existing errors to provide additional context.
274
-
-**`xerrors.Join`**: Use this to chain errors together _without_ capturing stack traces. This is most appropriate for creating sentinel errors.
280
+
-**`xerrors.Join`**: Use this to chain errors together _without_ capturing stack traces.
275
281
-**`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