Translate errors at boundaries
Translate errors at boundaries
An application boundary separates a component from its callers. Translate implementation-specific errors into stable domain errors when the caller should not depend on internal details. Preserve a cause with %w only when exposing that cause is part of the contract. Handle an error at the layer that can make a meaningful decision.
package main
import ( "errors" "fmt")
var errStorageMissing = errors.New("storage missing")var ErrNotFound = errors.New("not found")
func translate(err error) error { if errors.Is(err, errStorageMissing) { return ErrNotFound } return err}func main() { e := translate(fmt.Errorf("lookup: %w", errStorageMissing)) fmt.Println(e) fmt.Println(errors.Is(e, ErrNotFound), errors.Is(e, errStorageMissing))}The translator recognizes the wrapped storage failure and returns a public condition instead. It deliberately does not preserve that internal cause. Unknown errors pass through in this small internal example; at an external boundary they may require a separate safe translation.
Expected output:
not foundtrue falseChoose a safe public message
package main
import ( "errors" "fmt")
var ErrDenied = errors.New("access denied")
func publicMessage(err error) string { if err == nil { return "ok" } if errors.Is(err, ErrDenied) { return "not allowed" } return "operation failed"}func main() { fmt.Println(publicMessage(nil)) fmt.Println(publicMessage(fmt.Errorf("policy: %w", ErrDenied))) fmt.Println(publicMessage(errors.New("internal detail")))}This function produces a display message, not a new error value. The generic fallback avoids exposing internal detail to external users. Keep appropriate internal diagnostics at a trusted boundary, redact sensitive data, and avoid logging the same failure repeatedly as it propagates. Retry only when the error and operation contract justify it.
Expected output:
oknot allowedoperation failedTry it locally
Define ErrInvalid and a function status(err error) string returning "ok" for nil, "bad input" for a match with ErrInvalid and "failed" otherwise. Print each case, including a wrapped ErrInvalid.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Errors and cleanup 07: Translate errors at boundaries
Check the lesson objective before moving on.
Why translate a storage error to a domain sentinel?
What should an external message do with unknown sensitive internal details?