Skip to content

Errors

Zinc uses normal Go error returns for handler failure flow.

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.

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.

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

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

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).

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()
}

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.