0 day streak
go / intermediate
Snippet

Defining Custom Error Types with Unwrap Method for Error Wrapping

In Go, custom errors can wrap underlying errors. By implementing the `Unwrap() error` method on a custom error struct, you integrate it with the standard `errors` package, allowing functions like `errors.Unwrap` or `errors.Is` to traverse the chain of errors.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main
import (
"errors"
"fmt"
)
type QueryError struct {
Query string
Err error
}
func (e *QueryError) Error() string {
return fmt.Sprintf("query %q failed: %v", e.Query, e.Err)
}
func (e *QueryError) Unwrap() error {
return e.Err
}
func runQuery() error {
baseErr := errors.New("connection timeout")
return &QueryError{Query: "SELECT * FROM users", Err: baseErr}
}
func main() {
err := runQuery()
if err != nil {
fmt.Println("Error:", err)
if unwrapped := errors.Unwrap(err); unwrapped != nil {
fmt.Println("Unwrapped:", unwrapped)
}
}
}
Breakdown
1
type QueryError struct {
Declares a custom error struct holding contextual query data and the underlying error.
2
func (e *QueryError) Error() string {
Implements the error interface by returning a formatted description of the error.
3
func (e *QueryError) Unwrap() error {
Implements the Unwrap method, allowing the standard library to inspect the underlying error.