apperr.go69 lines, 2.1 KB
| 1 | // Package apperr defines the errors our services share. They describe what |
| 2 | // went wrong, not how to report it: HTTP, and later gRPC, map them to codes. |
| 3 | package apperr |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "maps" |
| 8 | "slices" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | // Wrap these to add detail: fmt.Errorf("account %s: %w", id, apperr.ErrNotFound). |
| 13 | var ( |
| 14 | // ErrNotFound means the requested resource doesn't exist. |
| 15 | ErrNotFound = errors.New("not found") |
| 16 | // ErrConflict means the request clashes with the current state, such as |
| 17 | // creating something that already exists. |
| 18 | ErrConflict = errors.New("conflict") |
| 19 | // ErrUnauthenticated means the caller didn't prove who they are: a wrong |
| 20 | // password, or a token that's missing, invalid, expired or revoked. |
| 21 | ErrUnauthenticated = errors.New("unauthenticated") |
| 22 | // ErrForbidden means we know who the caller is, and they may not do this. |
| 23 | ErrForbidden = errors.New("forbidden") |
| 24 | ) |
| 25 | |
| 26 | // ValidationError reports which fields of a request are invalid, and why. |
| 27 | type ValidationError struct { |
| 28 | Fields map[string]string |
| 29 | } |
| 30 | |
| 31 | // Add records a problem with one field. |
| 32 | func (v *ValidationError) Add(field, problem string) { |
| 33 | if v.Fields == nil { |
| 34 | v.Fields = make(map[string]string) |
| 35 | } |
| 36 | v.Fields[field] = problem |
| 37 | } |
| 38 | |
| 39 | // Err returns v if any field is invalid, and nil otherwise. Always return |
| 40 | // Err(), never v itself: a nil *ValidationError inside an error isn't nil. |
| 41 | func (v *ValidationError) Err() error { |
| 42 | if len(v.Fields) == 0 { |
| 43 | return nil |
| 44 | } |
| 45 | return v |
| 46 | } |
| 47 | |
| 48 | func (v *ValidationError) Error() string { |
| 49 | fields := slices.Sorted(maps.Keys(v.Fields)) |
| 50 | return "invalid input: " + strings.Join(fields, ", ") |
| 51 | } |
| 52 | |
| 53 | // RuleError means a request was valid, but breaks a business rule, like |
| 54 | // spending more than a wallet holds. Code is a stable reason, like |
| 55 | // insufficient_funds, that clients can branch on. |
| 56 | type RuleError struct { |
| 57 | Code string |
| 58 | Message string |
| 59 | } |
| 60 | |
| 61 | // NewRule returns a RuleError. Declare one per rule as a package variable, and |
| 62 | // wrap it to add detail: fmt.Errorf("wallet %s: %w", id, ErrInsufficientFunds). |
| 63 | func NewRule(code, message string) *RuleError { |
| 64 | return &RuleError{Code: code, Message: message} |
| 65 | } |
| 66 | |
| 67 | func (e *RuleError) Error() string { |
| 68 | return e.Message |
| 69 | } |