Custom Errors Unwrap Their Cause
Define a custom error with an Unwrap method so errors.Unwrap peels one layer at a time and errors.Is still matches the sentinel cause underneath.
Code
package main
import (
"errors"
"fmt"
)
var errStoreDown = errors.New("store unavailable")
type QueryError struct {
Op string
Cause error
}
// custom errors expose their cause through Unwrap
func (e *QueryError) Unwrap() error { return e.Cause }
func (e *QueryError) Error() string {
return e.Op + ": " + e.Cause.Error()
}
func main() {
err := &QueryError{Op: "load", Cause: errStoreDown}
fmt.Println("printed:", err.Error())
// peel one layer manually
fmt.Println("unwrap once:", errors.Unwrap(err))
// QueryError wraps one layer, so the second unwrap hits nil
fmt.Println("unwrap twice:", errors.Unwrap(errors.Unwrap(err)))
// errors.Is walks the Unwrap chain to reach the sentinel
fmt.Println("is store down?", errors.Is(err, errStoreDown))
}What the wrapper does
QueryError carries an operation name plus a Cause, and its Unwrap method hands that cause to the errors package. The demo prints the composed message, then calls errors.Unwrap once to reveal the sentinel underneath and once more to show the chain ending in nil.
errors.Is walks exactly that chain: it asks each layer whether it matches errStoreDown, unwrapping as it goes. The printed true is what makes custom errors interoperable with code that only knows the sentinel.
Practical notes
- Without an Unwrap method, errors.Unwrap returns nil and errors.Is stops matching.
- Error() composes Op with the cause text, so printing stays readable while unwrapping stays structural.
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How does errors.Is reach errStoreDown through QueryError?
- QueryError implements Unwrap() returning its Cause field, so errors.Unwrap peels the wrapper and errors.Is follows that chain until it matches the store unavailable sentinel.
Report a problem with this exampleOpens a pre-filled issue on GitHub.