Design a consistent Go error handling strategy with wrapping, sentinel errors, and clean boundaries between layers.
## CONTEXT My Go codebase has inconsistent error handling, with mixed use of fmt.Errorf, custom types, and ad hoc strings. I want a coherent strategy using error wrapping, sentinel and typed errors, and clear rules for where to handle versus propagate. Assume Go errors.Is, errors.As, and wrapping with percent w. ## ROLE Act as a Go API designer who treats errors as part of the contract. You know when a sentinel error, a typed error, or a wrapped message is appropriate, and you keep error handling readable rather than ceremonial. ## RESPONSE GUIDELINES - Recommend wrapping with context at each layer boundary. - Distinguish sentinel errors, typed errors, and opaque errors clearly. - Keep error messages lowercase and free of trailing punctuation. - Show how callers inspect errors with errors.Is and errors.As. ## TASK CRITERIA ### Establish Error Categories - Define sentinel errors for conditions callers branch on. - Create typed errors when callers need structured details. - Use opaque wrapped errors for everything else. - Document which categories cross package boundaries. ### Wrap With Context - Add who and what context when wrapping at each layer. - Avoid duplicating context already present in the wrapped error. - Preserve the original error with the percent w verb. - Keep messages concise and free of redundant phrasing. ### Handle At The Right Layer - Define where transient errors are retried versus surfaced. - Decide which layer logs and which only propagates. - Avoid logging and returning the same error twice. - Translate internal errors to client-safe forms at the edge. ### Map To Transport - Convert errors to HTTP status codes or gRPC statuses at the boundary. - Strip internal detail from client-facing error responses. - Include actionable codes for clients that automate handling. - Keep validation errors distinct from server faults. ### Test And Document - Show tests that assert specific errors with errors.Is and As. - Document the exported errors and types as part of the API. - Recommend lint rules that catch unwrapped or swallowed errors. - Provide examples of correct propagation across layers. ## ASK THE USER FOR - Representative functions showing your current error handling. - The layers in your codebase such as transport, service, and storage. - How clients consume your errors today. - Any retry, logging, or observability requirements.
Or press ⌘C to copy