Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Middleware

Middleware for Errors and Timeouts in Gin

Centralize error responses with c.Error and an error middleware, limit request time with context deadlines, cap body sizes, and compress responses. Includes runnable net/http stand-ins for each pattern.

Two jobs show up in every production service: turning failures into consistent responses, and making sure no single request can hold the server hostage. Both are best done in middleware, so individual handlers stay short and honest. This closing lesson of the middleware chapter shows an error-handling middleware built on c.Error, request timeouts with context, body size limits and response compression. It builds on Writing Custom Middleware and the error envelope from HTTP Status Codes and Error Responses.

Gin does not run on this site, so Gin code is read-only. The stand-ins are runnable Go programs on the standard library that reproduce each pattern.

Central error handling with c.Error

Handlers that format their own errors repeat themselves and drift apart. Instead, a handler can attach the error and return, and one middleware decides how to answer:

Go
type AppError struct {
	Status  int
	Code    string
	Message string
	Err     error // internal cause, never sent to the client
}

func (e *AppError) Error() string { return e.Code + ": " + e.Message }
func (e *AppError) Unwrap() error { return e.Err }

func NotFound(msg string) *AppError   { return &AppError{404, "not_found", msg, nil} }
func Conflict(msg string) *AppError   { return &AppError{409, "conflict", msg, nil} }

func ErrorHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next() // run the handlers first

		if len(c.Errors) == 0 || c.Writer.Written() {
			return
		}
		err := c.Errors.Last().Err

		var app *AppError
		if errors.As(err, &app) {
			c.JSON(app.Status, gin.H{"error": gin.H{"code": app.Code, "message": app.Message}})
			return
		}
		log.Printf("unhandled error on %s: %v", c.FullPath(), err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": gin.H{"code": "internal", "message": "something went wrong"},
		})
	}
}

A handler then reads:

Go
func (h *BookHandler) Get(c *gin.Context) {
	book, err := h.store.Find(c.Param("id"))
	if err != nil {
		_ = c.Error(err)   // record and let the middleware answer
		return
	}
	c.JSON(http.StatusOK, book)
}

Four details:

  • The middleware runs its logic after c.Next(), because errors appear only once handlers ran.
  • c.Writer.Written() guards against a double response when the handler already wrote one.
  • Unknown errors become a generic 500, and the real error is logged. Clients never see internals.
  • Install it near the top: r.Use(gin.Recovery(), ErrorHandler()). Recovery then also covers panics inside the error handler's own work.

Gin also lets you tag an error with a type (c.Error(err).SetType(gin.ErrorTypePublic)) and attach metadata with SetMeta; the pattern above with your own error type is usually clearer.

Stand-in: error middleware

The runnable program below mirrors this design. Handlers return an error through a custom handler type (the standard library has no c.Error), and one wrapper maps it to a response. Three requests demonstrate a typed error, a plain internal error and success.

Go Stand-in: one place for error 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.

Handlers contain no JSON formatting at all. Changing the error shape later means editing one function.

Request timeouts

A slow database query or a stuck downstream call can pile up goroutines until the server falls over. The fix is a deadline: every request gets a context that expires, and slow operations must honor it. In Gin, wrap the request context:

Go
func Timeout(d time.Duration) gin.HandlerFunc {
	return func(c *gin.Context) {
		ctx, cancel := context.WithTimeout(c.Request.Context(), d)
		defer cancel()
		c.Request = c.Request.WithContext(ctx)
		c.Next()
	}
}

Handlers pass c.Request.Context() down to every database and HTTP call (db.WithContext(ctx), http.NewRequestWithContext). When the deadline passes, those calls return context.DeadlineExceeded, and your error middleware can map it to 504 Gateway Timeout or 503:

Go
if errors.Is(err, context.DeadlineExceeded) {
	c.JSON(http.StatusGatewayTimeout, gin.H{"error": gin.H{"code": "timeout"}})
	return
}

Important limits: a context deadline is cooperative. Code that ignores the context keeps running. For a hard server-wide limit also set ReadHeaderTimeout, ReadTimeout, WriteTimeout and IdleTimeout on http.Server (covered in the deployment chapter). Third-party wrappers like gin-contrib/timeout write a 408/504 response for you, but they still cannot kill a goroutine that does not check the context.

Stand-in: a deadline in action

This program runs a "slow query" that respects the context. Request one finishes within its budget; request two exceeds it and the middleware maps the error to a 504.

Go Stand-in: a request timeout with context

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 slow request did not wait the full two seconds: the context cut it off at 100 ms. That is exactly what you want from Timeout plus context-aware calls.

Limiting request body size

Without a limit, a client can post gigabytes and exhaust memory. Cap the body early:

Go
func MaxBody(n int64) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, n)
		c.Next()
	}
}

r.Use(MaxBody(1 << 20)) // 1 MiB

When a handler reads past the limit, binding returns an error (http: request body too large), which you should map to 413 Payload Too Large. MaxBytesReader also tells the server to close the connection after the response. Uploads get their own larger limit; see File Uploads and Downloads.

Compression

JSON and HTML compress very well. The gin-contrib/gzip package adds a one-line middleware:

Go
import "github.com/gin-contrib/gzip"

r.Use(gzip.Gzip(gzip.DefaultCompression))

Skip already compressed content (images, video, archives). In production a reverse proxy such as Nginx or Cloudflare often does compression for you, which is simpler and cheaper for the application.

Putting the chain together

A sensible starting order for an API:

Go
r := gin.New()
r.Use(
	gin.Recovery(),        // 1. catch panics from everything below
	RequestID(),           // 2. every log line gets an id
	gin.Logger(),          // 3. log the final status
	SecurityHeaders(),     // 4. cheap response headers
	MaxBody(1<<20),        // 5. reject giant bodies early
	Timeout(10*time.Second),
	ErrorHandler(),        // 6. turns c.Errors into JSON
)

Order each item by asking "what must be able to see the result of the others?". The error handler sits last (innermost) among the global set because its post-Next code runs first on the way out, writing the response before the Logger reads the status.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does an error-handling middleware do its work after c.Next()?

    Errors are recorded by the handlers. The middleware inspects c.Errors once they have finished.
  2. 2. What does a context deadline do to code that never checks the context?

    Only operations that watch ctx.Done (database drivers, HTTP clients, your own selects) stop at the deadline.
  3. 3. Which status fits a request body that exceeds http.MaxBytesReader's limit?

    413 tells the client the body was larger than the server allows.
  4. 4. Which details should the error middleware send to the client for an unexpected error?

    Internal errors can leak secrets; log them and respond generically.

Summary

  • Record errors with c.Error(err) and answer in one ErrorHandler middleware that runs after c.Next().
  • Use a typed AppError (status, code, message) and errors.As; hide unknown errors behind a generic 500.
  • Give each request a context deadline and pass c.Request.Context() to every slow call; set server timeouts too.
  • Cap bodies with http.MaxBytesReader, compress with gzip (or at the proxy).
  • Order middleware deliberately: Recovery outermost, error handler innermost.

Next: back to the Gin course overview for the next chapters on templates, databases and security.