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:
ErrBadRequestErrUnauthorizedErrForbiddenErrNotFoundErrMethodNotAllowedErrUnprocessableEntityErrInternalServerError
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β
- First Route for a small returned-error example.
- Configuration for
Config.ErrorHandler. - Errors API for predefined HTTP errors.