Gin project: a complete REST API · 5 MIN READ
One error envelope: RFC 9457 problem details mapped from domain errors in one middleware
Return application/problem+json for every failure by mapping a small domain error taxonomy to HTTP statuses in a single Gin middleware.
By now each notes handler writes its own gin.H{"error": ...}. Clients parse several shapes, someone eventually returns err.Error() and leaks a database host, and nobody can list which statuses an endpoint produces. RFC 9457 supplies a standard envelope. A taxonomy in the domain and one mapping function supply the discipline. The errors-testing lesson established one response owner; this lesson gives that owner a contract.
gin · A MAP OF THE IDEA
- Define domain errors
- Handlers call c.Error
- Map once in middleware
- Render problem+json
Useful when
- Clients parse one documented error shape and branch on a stable type URI.
- Internal error text stays in logs by construction.
- Adding a route cannot add a new, undocumented error format.
Watch out
- An unmapped new error kind silently becomes a 500 unless a test checks coverage.
- A handler that writes before failing leaves the middleware able only to log.
Implementation & operation cost: A small taxonomy, one mapping function and a middleware; existing handlers change from writing JSON to returning after c.Error.
Name failures in the domain, not in HTTP
The notes package defines what can go wrong in business terms: ErrNotFound, ErrConflict and ErrForbidden as sentinel values, and *ValidationError as a type that carries field-level reasons. Services wrap them with fmt.Errorf and %w to add context such as the note ID, and the wrapped chain still matches. The domain does not import net/http and does not know that 404 exists; a CLI or a queue worker can use the same errors. Malformed JSON is different: the domain never sees request bytes, so that error belongs to httpapi. Keep the taxonomy small. Four or five kinds cover most APIs, and each new kind is a decision about how clients should react, not a new spelling of "something failed".
Handlers record, the middleware responds
Every handler now ends a failure with c.Error(err) and returns; none of them chooses a status. The problems middleware calls c.Next, looks at the last recorded error and asks problemFor, the only mapping table in the service, for a Problem. It logs the cause of server errors, skips writing if a handler already committed a response, and renders application/problem+json. NoRoute records ErrNotFound, so unknown paths get the same envelope.
package main
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/gin-gonic/gin"
)
// ---- internal/notes: the error taxonomy. No HTTP here. ----
var (
ErrNotFound = errors.New("notes: not found")
ErrConflict = errors.New("notes: conflicts with current state")
ErrForbidden = errors.New("notes: caller may not do this")
)
type FieldError struct {
Field string `json:"field"`
Reason string `json:"reason"`
}
// ValidationError carries messages written for clients; it is safe to expose.
type ValidationError struct{ Fields []FieldError }
func (e *ValidationError) Error() string {
return fmt.Sprintf("notes: %d invalid fields", len(e.Fields))
}
// ---- internal/httpapi: the one place that maps errors to HTTP. ----
var errMalformedBody = errors.New("httpapi: malformed body")
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
Errors []FieldError `json:"errors,omitempty"`
}
const typeBase = "https://example.com/problems/"
func problemFor(err error) Problem {
if ve, ok := errors.AsType[*ValidationError](err); ok {
return Problem{Type: typeBase + "validation", Title: "Invalid note", Status: http.StatusUnprocessableEntity,
Detail: "One or more fields are invalid.", Errors: ve.Fields}
}
switch {
case errors.Is(err, errMalformedBody):
return Problem{Type: typeBase + "malformed-body", Title: "Malformed request body", Status: http.StatusBadRequest}
case errors.Is(err, ErrNotFound):
return Problem{Type: typeBase + "not-found", Title: "Note not found", Status: http.StatusNotFound}
case errors.Is(err, ErrConflict):
return Problem{Type: typeBase + "conflict", Title: "Note conflicts with current state", Status: http.StatusConflict,
Detail: "Another note already uses this title."}
case errors.Is(err, ErrForbidden):
return Problem{Type: typeBase + "forbidden", Title: "Action not allowed", Status: http.StatusForbidden}
}
return Problem{Type: "about:blank", Title: "Internal Server Error", Status: http.StatusInternalServerError}
}
func problems(logf func(format string, args ...any)) gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if len(c.Errors) == 0 {
return
}
err := c.Errors.Last().Err
p := problemFor(err)
if p.Status >= http.StatusInternalServerError {
logf("%s %s: %v", c.Request.Method, c.Request.URL.Path, err) // full cause, server side only
}
if c.Writer.Written() {
return // a handler already committed a response; never write a second one
}
p.Instance = c.Request.URL.Path
c.Header("Content-Type", "application/problem+json")
c.JSON(p.Status, p)
}
}
// Handlers record the cause and return. They never choose a status for an error.
func getNote(c *gin.Context) {
_ = c.Error(fmt.Errorf("load note %s: %w", c.Param("id"), ErrNotFound))
}
func createNote(c *gin.Context) {
var in struct {
Title *string `json:"title"`
}
if err := c.ShouldBindJSON(&in); err != nil {
_ = c.Error(fmt.Errorf("%w: %v", errMalformedBody, err))
return
}
if in.Title == nil || strings.TrimSpace(*in.Title) == "" {
_ = c.Error(&ValidationError{Fields: []FieldError{{Field: "title", Reason: "must not be blank"}}})
return
}
_ = c.Error(fmt.Errorf("insert note: %w", ErrConflict))
}
func deleteNote(c *gin.Context) {
_ = c.Error(fmt.Errorf("delete note %s owned by u2: %w", c.Param("id"), ErrForbidden))
}
func exportNotes(c *gin.Context) {
_ = c.Error(errors.New(`pq: password authentication failed for user "notes_rw" at 192.0.2.10:5432`))
}
func main() {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(problems(func(format string, args ...any) { fmt.Printf("log: "+format+"\n", args...) }))
r.NoRoute(func(c *gin.Context) { _ = c.Error(ErrNotFound) })
r.GET("/notes/:id", getNote)
r.POST("/notes", createNote)
r.DELETE("/notes/:id", deleteNote)
r.GET("/export", exportNotes)
requests := []struct{ method, path, body string }{
{"GET", "/notes/n9", ""},
{"POST", "/notes", `{"title":`},
{"POST", "/notes", `{"title":" "}`},
{"POST", "/notes", `{"title":"Groceries"}`},
{"DELETE", "/notes/n1", ""},
{"GET", "/export", ""},
{"GET", "/nowhere", ""},
}
for _, rq := range requests {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(rq.method, rq.path, strings.NewReader(rq.body)))
fmt.Println(w.Code, w.Header().Get("Content-Type"), w.Body.String())
}
}problemFor checks the typed error first with errors.AsType, the generic counterpart of errors.As in the Go 1.27 standard library, then the sentinels with errors.Is; both see through the %w wrapping, so "load note n9: notes: not found" still maps to 404. The 400 for truncated JSON never repeats the decoder message. The 422 carries the field list from ValidationError, the one error type written for clients. The 500 shows the split: the log line has the full driver message, including user and host, while the body says only Internal Server Error. The last line is an unregistered path, which Gin routes through global middleware and the NoRoute handler, so it is a problem document rather than Gin's plain-text default.
The problem document, member by member
RFC 9457, which obsoletes RFC 7807, defines a JSON object served as application/problem+json. type is a URI reference that identifies the problem type and is what clients should branch on; when it is absent it means about:blank, and then title should be the standard phrase for the status code. title is a short summary of the type that should not change between occurrences except for localization. status is advisory and must match the real response status. detail explains this occurrence and should help the client correct the request, not debug the server. instance identifies the occurrence. Extension members such as errors are allowed, and clients must ignore extensions they do not understand.
{
"type": "https://example.com/problems/validation",
"title": "Invalid note",
"status": 422,
"detail": "One or more fields are invalid.",
"instance": "/notes",
"errors": [
{"field": "title", "reason": "must not be blank"}
]
}This is the 422 body from the program, pretty-printed. The type URI is a stable identifier under your control and can resolve to human documentation; example.com is a placeholder. title stays the same for every validation failure, while detail and the errors extension describe this request. instance here is the request path; a request ID or a urn:uuid value is also acceptable if support tooling needs to find the matching log line.
What must never reach the body
The text of an arbitrary error is written for developers: it contains SQL fragments, hostnames, user names, file paths and library versions. Public text therefore comes only from the mapping table or from error types designed to be public, such as ValidationError; an unrecognized error becomes a 500 with about:blank and no detail. Log the cause with a request ID and return that ID as an extension member if support needs to correlate. Choose between 403 and 404 deliberately: when the caller may not even know a note exists, answer 404 so the status does not confirm it; use 403 when the caller can see the note but may not perform this action. Two Gin details make the middleware work. Setting Content-Type before c.JSON is preserved, because Gin's JSON renderer only sets the header when it is absent. And when a handler has already written, the middleware must only log, because a second write cannot change a status that is already on the wire.
Test the envelope as a contract
For each member of the taxonomy and for one unknown error, send a request through ServeHTTP and assert the status, the Content-Type and the decoded body; the API-tests lesson builds this table. Add one test that fails when an exported sentinel has no mapping, so a new error kind cannot silently become a 500. Assert that 500 bodies contain no detail at all, since that is the regression that leaks credentials. Clients should branch on type, so changing a type URI is a breaking change; changing title wording is not.
TAKE THIS WITH YOU
Let handlers call c.Error with domain errors, map them in one middleware with errors.Is and errors.AsType to application/problem+json, and never copy an unrecognized error's text into the body.
Check your understanding
In the notes API, where should a wrapped notes.ErrConflict become a 409 application/problem+json response?
Go to the source
Progress stays in this browser. No account needed.