Errors
Zinc uses normal Go error returns for handler failure flow.
At a glance
Section titled “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
Section titled “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
Section titled “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
Section titled “Predefined errors”Zinc ships a broad set of predefined HTTP errors, including:
ErrBadRequestErrUnauthorizedErrForbiddenErrNotFoundErrMethodNotAllowedErrUnprocessableEntityErrInternalServerError
You can also create your own with NewError(code).
Abort helpers
Section titled “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
Section titled “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
Section titled “See also”- Your First Route for a small returned-error example.
- Configuration for
Config.ErrorHandler. - Errors API for predefined HTTP errors.
