Skip to main content

Errors

Zinc uses normal Go error returns for handler failure flow.

At a glance​

app.Get("/users/:id", func(c *zinc.Context) error {
user, err := findUser(c.Param("id"))
if err != nil {
return zinc.ErrNotFound.WithMessage("user not found")
}
return c.JSON(user)
})

Return errors from handlers and middleware. Let one app-level error handler decide how errors become HTTP responses.

Returning errors​

app.Get("/users/:id", func(c *zinc.Context) error {
return zinc.ErrNotFound
})

If the returned error is an HTTPError, Zinc writes the associated status and message.

Structured HTTP errors​

Build more specific errors with WithMessage, WithCause, WithMeta, and WithHeader.

return zinc.ErrBadRequest.
WithMessage("invalid user payload").
WithCause(err).
WithMeta("field", "email")

Predefined errors​

Zinc ships a broad set of predefined HTTP errors, including:

  • ErrBadRequest
  • ErrUnauthorized
  • ErrForbidden
  • ErrNotFound
  • ErrMethodNotAllowed
  • ErrUnprocessableEntity
  • ErrInternalServerError

You can also create your own with NewError(code).

Abort helpers​

For explicit short-circuiting inside handlers or middleware:

  • AbortWithStatus(code)
  • AbortWithJSON(code, value)
  • Fail(err)

Example:

func requireAuth(c *zinc.Context) error {
if c.GetHeader("Authorization") == "" {
return c.AbortWithStatus(zinc.StatusUnauthorized)
}
return c.Next()
}

Custom error handlers​

Override Zinc’s default error writer with Config.ErrorHandler.

app := zinc.NewWithConfig(zinc.Config{
ErrorHandler: func(c *zinc.Context, err error) {
_ = c.Status(zinc.StatusInternalServerError).JSON(zinc.Map{
"error": err.Error(),
})
},
})

That gives you one place to standardize API error envelopes.

See also​