Documentation
¶
Overview ¶
Package apierror provides typed HTTP errors and a Fiber ErrorHandler that renders them (and *fiber.Error, and unknown errors) as the standard JSON envelope. Handlers and services return an *Error; bootstrap wires Handler by default so the response is consistent.
Index ¶
- func Handler(c *fiber.Ctx, err error) error
- type Error
- func BadRequest(message string) *Error
- func Conflict(message string) *Error
- func Forbidden(message string) *Error
- func Internal(message string) *Error
- func New(status int, code, message string) *Error
- func NotFound(message string) *Error
- func TooManyRequests(message string) *Error
- func Unauthorized(message string) *Error
- func UnprocessableEntity(message string) *Error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Handler ¶
Handler is a fiber.ErrorHandler that renders errors as the standard JSON envelope: *Error at its status with its code, *fiber.Error at its code, and any other error as a generic 500 (the raw message is not exposed).
Example ¶
Return a typed error from a handler; the ErrorHandler renders it as JSON.
package main
import (
"fmt"
"io"
"net/http/httptest"
"github.com/gofiber/fiber/v2"
"github.com/rahmadafandi/fibr/apierror"
)
func main() {
app := fiber.New(fiber.Config{ErrorHandler: apierror.Handler})
app.Get("/users/:id", func(c *fiber.Ctx) error {
return apierror.NotFound("user not found").WithCode("user_not_found")
})
resp, _ := app.Test(httptest.NewRequest("GET", "/users/9", nil))
body, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode)
fmt.Println(string(body))
}
Output: 404 {"code":404,"message":"user not found","error":"user_not_found","status":"error"}
Types ¶
type Error ¶
type Error struct {
Status int
Code string
Message string
Details any
// contains filtered or unexported fields
}
Error is a typed HTTP error: an HTTP status, a machine-readable code, a human message, optional details (rendered into "data"), and an optional wrapped cause (for errors.Is/As and logging; never serialized).
func TooManyRequests ¶
TooManyRequests returns a 429 Error.
func UnprocessableEntity ¶
UnprocessableEntity returns a 422 Error.
func (*Error) WithCode ¶
WithCode overrides the default machine code (e.g. "email_taken"). It returns a copy, so it is safe to call on shared/sentinel values.
func (*Error) WithDetails ¶
WithDetails attaches details rendered into the response "data" field. It returns a copy, so it is safe to call on shared/sentinel values.