Handlers and API errors
The status is part of the contract. The error text for the client is short. The chain for the journal is complete.
A handler translates a domain error into HTTP. The store must not know about the codes 404 and 409. It returns ErrNotFound or its own error. The handler decides:
нет пользователя 404
кривой JSON 400
почта занята 409
база недоступна 500
On a 500 the chain is written to the journal through %w and slog. The client gets a short JSON with no SQL and no paths on disk. err.Error() on the outside is a leak of details and an unstable contract: the text changed, and the client drifted apart.
The body is read with a limit. http.MaxBytesReader does not let someone send a gigabyte into a small JSON. A parse error is distinguished from a body that is too large if you want different statuses, but both cases are a problem of the request, not of the server.
Middleware is a function func(http.Handler) http.Handler. It is good for cross-cutting concerns: a request identifier, recovery after a panic, a journal, authentication. It is not good for hiding a business branch "if admin". A branch that depends on a concrete route lives in the handler. Otherwise it is impossible to see while reading the function.
A panic is caught by one middleware at the edge, the stack is written, and the answer is 500. This is so the process stays alive. It is not a way to return a validation error.
A repeated piece "join the parts of a message" is better as a function with a test than as a copied strings.Join across handlers. A small pure function is easy to check and does not drag in HTTP.
Practice
Who chooses 404
The store did not find a record. Who turns that into HTTP 404?
- The SQL driver
- The handler at the HTTP boundary
- The package fmt
- The client, by itself, from the error text
Join the context
Write
JoinErrors(parts []string) string. Join the non-empty pieces with": ", trimming spaces at the edges of each piece. Skip pieces that are empty or made of spaces. If there is nothing to join, return an empty string.What the client sees
The database returned an error with a table name and a server address. What do you put in the JSON for the client on a 500?
- The full err.Error(), so the client can debug more easily
- A short safe message, with the details only in the journal
- An empty response with no status
- The database password, so the client can reconnect itself