go / intermediate
Snippet
Defining Custom Error Types and Using errors.As
Custom error types in Go allow carrying structured context alongside the error message. By implementing the Unwrap method, the custom error integrates with Go's standard library wrapping mechanics, allowing errors.As to retrieve the specific custom error type from anywhere in the call chain.
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 mainimport ("errors""fmt")type QueryError struct {Query stringErr 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 execute() error {return &QueryError{Query: "SELECT * FROM users",Err: errors.New("connection timeout"),}}func main() {err := execute()var qErr *QueryErrorif errors.As(err, &qErr) {fmt.Printf("Query failed: %s\n", qErr.Query)}}
Breakdown
1
type QueryError struct { ... }
Defines a custom struct to hold context, such as the query string and the underlying error.
2
func (e *QueryError) Error() string
Implements the built-in error interface by returning a formatted description of the error.
3
func (e *QueryError) Unwrap() error
Exposes the underlying nested error, enabling standard library wrapping/unwrapping inspection functions.
4
errors.As(err, &qErr)
Checks if any error in the chain matches the target type, wrapping/unwrapping as needed, and binds it to qErr if a match is found.