Model domain services and error contracts
Model domain services and error contracts
A domain service coordinates a business operation such as reserving a quantity of stock. Model the invariant (a rule that must remain true) independently of HTTP or database details. Return errors that callers can classify using errors.Is or errors.As. Decide which categories are part of the public contract rather than exposing storage-specific errors accidentally.
package main
import ( "errors" "fmt")
var ErrInsufficient = errors.New("insufficient stock")var ErrQuantity = errors.New("invalid quantity")
func reserve(stock, qty int) (int, error) { if qty <= 0 { return stock, ErrQuantity } if qty > stock { return stock, fmt.Errorf("reserve %d: %w", qty, ErrInsufficient) } return stock - qty, nil}func main() { n, err := reserve(5, 2) fmt.Println(n, err) n, err = reserve(5, 6) fmt.Println(n, errors.Is(err, ErrInsufficient))}Assume nonnegative initial stock. A rejected request leaves stock unchanged. Wrapping with %w retains the error identity so the boundary can classify it without comparing strings. A real store must enforce the invariant atomically across concurrent requests; this pure calculation alone cannot prevent overselling.
Expected output:
3 <nil>5 trueTranslate errors at the boundary
package main
import ( "errors" "fmt")
var ErrMissing = errors.New("missing")
func status(err error) int { switch { case err == nil: return 200 case errors.Is(err, ErrMissing): return 404 default: return 500 }}func main() { fmt.Println(status(nil), status(fmt.Errorf("lookup: %w", ErrMissing)), status(errors.New("unexpected")))}The boundary chooses HTTP status; the domain does not return HTTP numbers. Unexpected internal errors should be logged with appropriate redaction and converted to a generic public response, not returned verbatim. Exposing a wrapped error can make its identity part of your API; choose intentionally.
Expected output:
200 404 500Try it locally
Implement withdraw(balance, amount int) for a nonnegative balance. Reject zero/negative amount and insufficient funds with distinct sentinel errors, leaving balance unchanged. Print the result for balance 10 and amount 4, then check the error categories for amounts 0 and 11.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Professional architecture 03: Model domain services and error contracts
Check the lesson objective before moving on.
Why use %w for a promised domain error?
Where should HTTP status mapping live?