liveBook · Manning

Error wrapping

As explained in 100 Go Mistakes and How to Avoid Them

Error wrapping is the practice of attaching contextual information to an error while preserving the underlying error for propagation and inspection.

Error wrapping adds context or marks an error while keeping the underlying error available to callers. For example, a permission-denied error can carry the user and resource involved, or be marked as forbidden so an HTTP handler can return 403. A wrapper can do both. section 7.2

Wrap or convert?

Given an error from bar, fmt.Errorf("bar failed: %w", err) adds context and preserves err for inspection. Using fmt.Errorf("bar failed: %v", err) adds context but does not make the source error available. Return err directly when neither a marker nor additional context is useful. section 7.2

Exposing the source error can couple callers to it. If callers should not depend on the underlying error, convert it instead of wrapping it. A custom error type can provide a marker and context, but makes the source available only if it exposes it, for example through a field or method. section 7.2 section 7.8

A direct type switch checks the returned error, not an error inside its wrapper. After a transaction function wraps a transient error, the switch misses it and the handler returns 400 instead of 503. Use errors.As to check types through the chain; its target must be a pointer. Use errors.Is to check error values through the chain. section 7.3 section 7.8

func handler(w http.ResponseWriter, r *http.Request) {
    // Get transaction ID
 
    amount, err := getTransactionAmount(transactionID)
    if err != nil {
        if errors.As(err, &transientError{}) {      #1
            http.Error(w, err.Error(),
                http.StatusServiceUnavailable)      #2
        } else {
            http.Error(w, err.Error(),
                http.StatusBadRequest)              #3
        }
        return
    }
 
    // Write response
}

The handler uses errors.As to recognize a transient error whether it is returned directly or wrapped. section 7.3

Wrapping also preserves diagnostic context without logging at every layer. If coordinate validation logs an error and its caller logs it again, one failure produces repeated messages. Returning the error directly avoids duplication but loses whether source or target coordinates failed. Wrap it with that context and let the caller handle it once. section 7.5

func GetRoute(srcLat, srcLng, dstLat, dstLng float32) (Route, error) {
    err := validateCoordinates(srcLat, srcLng)
    if err != nil {
        return Route{},
            fmt.Errorf("failed to validate source coordinates: %w",
                err)      #1
    }
 
    err = validateCoordinates(dstLat, dstLng)
    if err != nil {
        return Route{},
            fmt.Errorf("failed to validate target coordinates: %w",
                err)      #1
    }
 
    return getRoute(srcLat, srcLng, dstLat, dstLng)
}

Each validation failure is wrapped with its source or target context before propagation. section 7.5

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Contrasts direct returns, custom error types, wrapping and conversion, then shows how callers inspect wrapped errors.
Examples
Uses a permission-denied database query, a transaction HTTP handler and coordinate validation to illustrate wrapping decisions.
What you can do after
Apply it via fmt.Errorf with %w, and inspect wrapped types or values with errors.As or errors.Is.
How it connects
Connects error wrapping to error types, error values, error handling and logging.

Also explained in

Compare how 3 books explain error wrapping →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.