go / intermediate
Snippet
Defining and extracting custom error types with errors.As
This snippet shows how to define structured error types by implementing the Error interface and how to safely inspect and extract the structured data using errors.As. This is critical for robust domain error handling.
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
package mainimport ("errors""fmt")type ValidationError struct {Field stringMessage string}func (e *ValidationError) Error() string {return fmt.Sprintf("invalid %s: %s", e.Field, e.Message)}func validateUsername(name string) error {if len(name) < 3 {return &ValidationError{Field: "Username", Message: "too short"}}return nil}func main() {err := validateUsername("go")if err != nil {var valErr *ValidationErrorif errors.As(err, &valErr) {fmt.Printf("Validation failed on field: %s\n", valErr.Field)}}}
Breakdown
1
func (e *ValidationError) Error() string {
Implements the standard error interface for the custom ValidationError struct.
2
var valErr *ValidationError
Declares a pointer variable of the target error type.
3
if errors.As(err, &valErr) {
Checks if the error or any wrapped error is of the target type, extracting it if true.