CodeNebula
Go📦Standard Libraryintermediate

errors — Error Handling Utilities

Go · Standard Library · Run with go run

Explanation

The `errors` package provides `errors.New` (create a sentinel error), `errors.Is` (check error identity through a chain of wrapped errors), and `errors.As` (extract a specific error type from a chain). Together with `fmt.Errorf("%w", err)`, they form Go's structured error handling system.

Real-World Scenario

A storage layer returns a typed `*NotFoundError`. A service layer wraps it with context: `fmt.Errorf("getUser: %w", storageErr)`. The HTTP handler unwraps with `errors.As(err, &notFound)` to decide whether to return 404 or 500.

Quick Snippet

snippet.go
import "errors"

var ErrNotFound = errors.New("not found")

type ValidationError struct{ Field string; Msg string }
func (e *ValidationError) Error() string {
    return fmt.Sprintf("validation: %s %s", e.Field, e.Msg)
}

err := fmt.Errorf("user lookup: %w", ErrNotFound)

errors.Is(err, ErrNotFound) // true — unwraps chain

var ve *ValidationError
if errors.As(err, &ve) {
    fmt.Println("bad field:", ve.Field) // type-safe access
}

Full Example

errors_pkg.go
// Compile: go run errors_pkg.go
// Output:
//   wrapped: user lookup: not found
//   errors.Is ErrNotFound: true
//   errors.As ValidationError, field: email
package main

import (
	"errors"
	"fmt"
)

var ErrNotFound = errors.New("not found")

type ValidationError struct {
	Field string
	Msg   string
}

func (e *ValidationError) Error() string {
	return fmt.Sprintf("validation: %s %s", e.Field, e.Msg)
}

func main() {
	err := fmt.Errorf("user lookup: %w", ErrNotFound)
	fmt.Println("wrapped:", err)
	fmt.Println("errors.Is ErrNotFound:", errors.Is(err, ErrNotFound))

	verr := fmt.Errorf("bad input: %w", &ValidationError{Field: "email", Msg: "required"})
	var ve *ValidationError
	if errors.As(verr, &ve) {
		fmt.Println("errors.As ValidationError, field:", ve.Field)
	}
}
Run command
go run errors_pkg.go