Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Routing and Handlers

HTTP Status Codes and Error Responses in Gin

Pick the right HTTP status code in Gin handlers, return one consistent JSON error shape, abort safely with AbortWithStatusJSON, and map Go errors to responses with runnable stand-ins.

A client talking to your API learns two things from every response: whether the request worked (the status code) and, if it did not, why (the error body). Get both right and your API is pleasant to use; get them wrong and every caller writes guesswork. This lesson shows which status codes you will use constantly, how to give all your errors one shape, and how to turn Go errors into HTTP responses without scattering if statements everywhere.

It builds on Responses: JSON, XML, HTML and More and on Redirects and Custom 404 Pages. Later, binding and validation will produce many 400 and 422 errors, and middleware will centralize error handling.

Gin cannot run on this site, so Gin code is read-only. The runnable examples are Go stand-ins that use only the standard library and show the same ideas.

The status codes you will actually use

Codes are grouped by their first digit: 2xx success, 3xx redirect, 4xx the client made a mistake, 5xx the server failed. In practice a small set covers almost every API:

Code Constant Use it when
200 http.StatusOK A read or update succeeded and you return a body
201 http.StatusCreated A new resource was created (add a Location header)
204 http.StatusNoContent Success, nothing to return (usually DELETE)
400 http.StatusBadRequest The request is malformed: bad JSON, wrong type
401 http.StatusUnauthorized Not logged in or the credentials are wrong
403 http.StatusForbidden Logged in, but not allowed to do this
404 http.StatusNotFound The resource does not exist
409 http.StatusConflict The request clashes with current state (duplicate email)
422 http.StatusUnprocessableEntity Well-formed but fails validation rules
429 http.StatusTooManyRequests The caller is rate limited
500 http.StatusInternalServerError Your bug or an outage; never the client's fault

Always use the named constants. c.JSON(http.StatusCreated, book) reads better than c.JSON(201, book), and a typo in a constant fails to compile.

Two distinctions trip people up. 401 versus 403: 401 means "I do not know who you are", 403 means "I know who you are and the answer is no". 400 versus 422: 400 is for a body the server cannot parse, 422 is for a body that parses but breaks a business rule. Many teams use 400 for both, which is fine as long as you are consistent.

One error shape

Pick a single JSON structure for every error and stick to it. For example:

JSON
{
  "error": {
    "code": "validation_failed",
    "message": "title is required",
    "details": [{"field": "title", "problem": "required"}]
  }
}

code is a short stable string clients can switch on, message is for humans, and details is optional. In Gin you can define a helper once:

Go
type APIError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Details any    `json:"details,omitempty"`
}

func fail(c *gin.Context, status int, code, msg string) {
	c.AbortWithStatusJSON(status, gin.H{"error": APIError{Code: code, Message: msg}})
}

Now a handler stays short:

Go
func (h *BookHandler) Get(c *gin.Context) {
	book, err := h.store.Find(c.Param("id"))
	if errors.Is(err, ErrNotFound) {
		fail(c, http.StatusNotFound, "book_not_found", "no book with that id")
		return
	}
	if err != nil {
		fail(c, http.StatusInternalServerError, "internal", "something went wrong")
		return
	}
	c.JSON(http.StatusOK, book)
}

Never put the raw err.Error() of an internal failure in the response for 500s. It can leak SQL, file paths or secrets. Log the details on the server and send a generic message.

Abort versus return

c.JSON(...) followed by return ends your handler. But Gin may still have more handlers in the chain (middleware after yours, or later handlers on the route). c.Abort() stops the chain. c.AbortWithStatusJSON(status, body) writes the response and aborts in one call, which is why it is the right choice inside middleware (see Writing Custom Middleware). In a final handler, c.JSON plus return is enough.

A common bug is forgetting return after an error response:

Go
if err != nil {
	c.JSON(http.StatusBadRequest, gin.H{"error": "bad input"})
	// missing return: the code below still runs and tries to write a second response
}
c.JSON(http.StatusOK, result)

Gin logs a warning ("headers were already written") and the client receives the first response only, but any side effects below (a database write!) still happen.

Collecting errors with c.Error

Gin can also record errors on the context instead of writing them immediately:

Go
if err := h.store.Delete(id); err != nil {
	_ = c.Error(err)   // attach to the context
	return
}

c.Errors holds everything attached during the request. A middleware that runs after the handler can look at c.Errors.Last() and write one consistent response. That is the pattern we will build in Middleware: Errors and Timeouts; it keeps handlers free of repeated formatting code.

Mapping Go errors to statuses

Go has no exceptions, so handlers receive ordinary error values. Define sentinel errors or typed errors in your service layer and map them in one place:

Go
var (
	ErrNotFound = errors.New("not found")
	ErrConflict = errors.New("conflict")
	ErrInvalid  = errors.New("invalid input")
)

func statusFor(err error) (int, string) {
	switch {
	case errors.Is(err, ErrNotFound):
		return http.StatusNotFound, "not_found"
	case errors.Is(err, ErrConflict):
		return http.StatusConflict, "conflict"
	case errors.Is(err, ErrInvalid):
		return http.StatusUnprocessableEntity, "invalid"
	default:
		return http.StatusInternalServerError, "internal"
	}
}

errors.Is also sees through wrapped errors (fmt.Errorf("load book 7: %w", ErrNotFound)), so lower layers can add context without breaking the mapping.

Stand-in: an error-to-response mapper

The program below does exactly that with the standard library: a service returns wrapped errors, one function maps them to a status and the common JSON envelope, and unknown errors are hidden behind a generic message.

Go Stand-in: one place that turns errors into responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Look at id=9: the internal message mentioning a database address never reaches the client. The same writeError function would be your fail helper or error middleware in Gin.

Stand-in: forgetting to return

To see why return matters, run this stand-in. The handler writes an error, forgets to return, and still performs a "database write".

Go Stand-in: the missing return bug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The client sees a 400, but an empty record was saved. Gin has the same trap, so make return (or Abort in middleware) a habit right after every error response.

Success codes matter too

  • After creating something return 201 and a Location header: c.Header("Location", "/api/v1/books/"+id).
  • For deletes, 204 with c.Status(http.StatusNoContent) (no body) is the convention.
  • Do not return 200 with {"success": false}. Clients, caches and monitoring tools read the status line first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A logged-in user tries to delete another user's book. Which status is the best fit?

    The server knows who the user is (so not 401) and refuses the action. 403 means authenticated but not permitted.
  2. 2. Why should a 500 response avoid err.Error() of the underlying failure?

    Log internals on the server; give the client a generic message and a stable error code.
  3. 3. What is the difference between c.JSON(...) plus return and c.AbortWithStatusJSON(...)?

    Abort prevents later handlers (and middleware code after the call to Next) from continuing, which matters inside middleware.
  4. 4. Which Go function lets you detect ErrNotFound inside an error created with fmt.Errorf("load: %w", ErrNotFound)?

    errors.Is walks the chain of wrapped errors, so context can be added without losing the original sentinel.

Summary

  • Learn the common codes: 200, 201, 204, 400, 401, 403, 404, 409, 422, 429, 500.
  • Use one JSON error envelope with a stable code and a human message.
  • Always return after writing an error; use AbortWithStatusJSON in middleware.
  • Map Go errors (sentinels, errors.Is) to statuses in a single place and hide internals from 500 responses.
  • c.Error records errors so middleware can respond uniformly.

Next: Binding JSON and Forms turns request bodies into Go structs.