Skip to main content

Error Handling

Okapi provides a flexible error handling system with built-in support for standard JSON errors, custom error formats, and RFC 7807 Problem Details.

:::warning Note on error details in production

DefaultErrorHandler puts the underlying error's text into the details field of the response, and middleware such as the JWT authenticator passes its internal error through. Clients therefore learn exactly why a request failed — with a JWKS-backed setup that can include the JWKS URL and the network error behind it, which is useful reconnaissance against an internal endpoint.

If that matters for your deployment, install a custom ErrorHandler that logs the error server-side and omits details from the response. See Custom Error Handlers below.

:::

Return an Error, or Abort?​

An error returned from a handler or middleware is not shown to the client. It is logged, and the configured ErrorHandler answers with a generic 500 — because an error's text routinely carries internals such as driver messages, hostnames or file paths. If something has already been written to the response, the error is logged and nothing further is sent.

So return an error only when a generic 500 is the right answer. Everywhere else, respond with an Abort* helper, which lets you choose the status and the message.

Quick Start​

Use c.Abort* methods to immediately stop request processing and return an error response:

o := okapi.Default()

o.Post("/books", func(c *okapi.Context) error {
book := &Book{}
if err := c.Bind(book); err != nil {
return c.AbortBadRequest("Invalid request body", err)
}
// ... handle valid request
return c.Created(book)
})

Response:

{
"code": 400,
"message": "Invalid request body",
"details": "field Name is required",
"timestamp": "2026-02-09T21:34:17.290908+01:00"
}

The err argument is optional. When omitted, the message is used as the underlying error, so details repeats the message.

Available Error Methods​

Every standard 4xx and 5xx status has two helpers on *Context, which behave differently:

FamilySignatureBodyMarks the request aborted
Abort*AbortNotFound(msg string, err ...error) errorBuilt by the configured ErrorHandler (ErrorResponse, Problem Details or your own)Yes
Error*ErrorNotFound(body any) errorThe value you pass, written with c.JSON as isNo

Use Abort* for errors, so they all share one format. Use Error* when you need to send a specific body for an error status; it bypasses the ErrorHandler.

For Abort* helpers, an empty msg falls back to a default message for the status, and when err is omitted the message is used as the underlying error.

4xx client errors

StatusAbort helperError helper
400AbortBadRequestErrorBadRequest
401AbortUnauthorizedErrorUnauthorized
402AbortPaymentRequiredErrorPaymentRequired
403AbortForbiddenErrorForbidden
404AbortNotFoundErrorNotFound
405AbortMethodNotAllowedErrorMethodNotAllowed
406AbortNotAcceptableErrorNotAcceptable
407AbortProxyAuthRequiredErrorProxyAuthRequired
408AbortRequestTimeoutErrorRequestTimeout
409AbortConflictErrorConflict
410AbortGoneErrorGone
411AbortLengthRequiredErrorLengthRequired
412AbortPreconditionFailedErrorPreconditionFailed
413AbortRequestEntityTooLargeErrorRequestEntityTooLarge
414AbortRequestURITooLongErrorRequestURITooLong
415AbortUnsupportedMediaTypeErrorUnsupportedMediaType
416AbortRequestedRangeNotSatisfiableErrorRequestedRangeNotSatisfiable
417AbortExpectationFailedErrorExpectationFailed
418AbortTeapotErrorTeapot
421AbortMisdirectedRequestErrorMisdirectedRequest
422AbortValidationErrorErrorUnprocessableEntity
423AbortLockedErrorLocked
424AbortFailedDependencyErrorFailedDependency
425AbortTooEarlyErrorTooEarly
426AbortUpgradeRequiredErrorUpgradeRequired
428AbortPreconditionRequiredErrorPreconditionRequired
429AbortTooManyRequestsErrorTooManyRequests
431AbortRequestHeaderFieldsTooLargeErrorRequestHeaderFieldsTooLarge
451AbortUnavailableForLegalReasonsErrorUnavailableForLegalReasons

5xx server errors

StatusAbort helperError helper
500AbortInternalServerError, Abort(err)ErrorInternalServerError
501AbortNotImplementedErrorNotImplemented
502AbortBadGatewayErrorBadGateway
503AbortServiceUnavailableErrorServiceUnavailable
504AbortGatewayTimeoutErrorGatewayTimeout
505AbortHTTPVersionNotSupportedErrorHTTPVersionNotSupported
506AbortVariantAlsoNegotiatesErrorVariantAlsoNegotiates
507AbortInsufficientStorageErrorInsufficientStorage
508AbortLoopDetectedErrorLoopDetected
510AbortNotExtendedErrorNotExtended
511AbortNetworkAuthenticationRequiredErrorNetworkAuthenticationRequired

AbortNotModified() and ErrorNotModified() send a bodiless 304, and c.Error(code, message) writes message as a plain-text body.

// Through the ErrorHandler, request marked aborted
return c.AbortConflict("Book already exists")

// Your own body, as JSON
return c.ErrorConflict(map[string]string{"error": "book already exists"})

Generic Abort Helpers​

MethodResponse
AbortWithError(code int, err error)Through the ErrorHandler, with the status text as the message
AbortWithStatus(code int, message string)Always an ErrorResponse: message is the status text and your message goes into details. Ignores the ErrorHandler
AbortWithJSON(code int, body any)body as JSON. Ignores the ErrorHandler
AbortWithProblemDetail(problem *ProblemDetail)problem as application/problem+json. See Writing a Problem Detail Directly

All of them mark the request aborted. AbortWithError is useful when the status is only known at runtime, for example one relayed from an upstream service:

return c.AbortWithError(resp.StatusCode, err)

Aborting from Middleware​

Once an Abort* helper has answered, c.Next() runs no further handler and returns nil, so a middleware that aborts cannot accidentally reach the handler it refused. c.IsAborted() reports whether that has happened:

o.Use(func(c *okapi.Context) error {
if c.Header("X-API-Key") == "" {
return c.AbortUnauthorized("Missing API key")
}
return c.Next()
})

o.Use(func(c *okapi.Context) error {
err := c.Next()
if c.IsAborted() {
c.Logger().Info("request aborted", "path", c.Path())
}
return err
})

Error* helpers and other writers such as c.JSON do not mark the request aborted.

Status Code Utilities​

okapi.IsClientError(code), okapi.IsServerError(code) and okapi.IsError(code) report whether a status code is 4xx, 5xx, or either.

Field-Level Validation Errors​

AbortValidationErrors answers 422 with a list of per-field failures. It always uses Okapi's ValidationErrorResponse shape, regardless of the configured ErrorHandler:

return c.AbortValidationErrors([]okapi.ValidationError{
{Field: "email", Message: "must be a valid email", Value: in.Email},
{Field: "age", Message: "must be greater than 0"},
})

AbortValidationErrorsWithProblemDetail emits the same information as application/problem+json.

Custom Error Handlers​

Override the default error format by providing a custom error handler:

o := okapi.Default().With(
okapi.WithErrorHandler(func(c *okapi.Context, code int, message string, err error) error {
return c.JSON(code, map[string]any{
"success": false,
"error": map[string]any{
"code": code,
"message": message,
"details": err.Error(),
},
})
}),
)

Response:

{
"success": false,
"error": {
"code": 400,
"message": "Invalid request body",
"details": "field Name is required"
}
}

To stop leaking internals, log err and leave it out of the response:

okapi.WithErrorHandler(func(c *okapi.Context, code int, message string, err error) error {
if err != nil {
c.Logger().Error("request failed", "code", code, "error", err)
}
return c.JSON(code, map[string]any{"code": code, "message": message})
})

err can be nil — notably for the generic 500 produced when a handler returns an error — so guard against it before calling err.Error().

A handler can also be installed for a single request with c.SetErrorHandler(handler), which takes precedence over the application-wide one. Any ErrorHandler works, including the built-in ones:

o.Get("/legacy", func(c *okapi.Context) error {
c.SetErrorHandler(okapi.DefaultErrorHandler)
return c.AbortNotFound("Gone for good")
})

To go back to the built-in ErrorResponse format after installing another handler, use okapi.WithDefaultErrorHandler() or o.WithDefaultErrorHandler().

:::note OpenAPI documentation

Okapi documents the error responses it adds to routes (such as the 400 for a binding failure) with the schema of the configured handler: ErrorResponse or ProblemDetail. It cannot know what a custom WithErrorHandler writes, so those responses are documented without a body. A handler set with c.SetErrorHandler is not reflected in the docs. See Typed routes.

:::

RFC 7807 Problem Details​

For APIs requiring standards-compliant error responses, Okapi supports RFC 7807 Problem Details.

Basic Setup​

o := okapi.Default()
o.WithSimpleProblemDetailErrorHandler()

Each o.With*ErrorHandler method also exists as an option, for example okapi.New(okapi.WithSimpleProblemDetailErrorHandler()).

This is WithProblemDetailErrorHandler(nil), whose defaults are Format: ErrorFormatProblemJSON, TypePrefix: "about:blank", IncludeInstance: true and IncludeTimestamp: true.

Response (Content-Type: application/problem+json) for c.AbortBadRequest("Invalid request body", err):

{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Invalid request body",
"instance": "/books",
"timestamp": "2026-02-09T21:42:49+01:00"
}

detail is the message you passed to the Abort* helper. The underlying error's text is used only when the message equals the status text, as with AbortWithError.

Advanced Configuration​

Customize the Problem Details output with additional fields and options:

o := okapi.Default()
o.WithProblemDetailErrorHandler(&okapi.ErrorHandlerConfig{
Format: okapi.ErrorFormatProblemJSON,
TypePrefix: "https://api.example.com/errors/",
IncludeInstance: true,
IncludeTimestamp: true,
CustomFields: map[string]any{
"api_version": "v1.0.0",
"support_url": "https://support.example.com",
},
})

Response:

{
"type": "https://api.example.com/errors/",
"title": "Bad Request",
"status": 400,
"detail": "Invalid request body",
"instance": "/books",
"timestamp": "2026-02-09T21:42:49+01:00",
"api_version": "v1.0.0",
"support_url": "https://support.example.com"
}

TypePrefix is written to type as given — no per-status slug is appended. Point it at a single document describing your error format, or install a custom ErrorHandler if you need one URI per problem type.

Configuration Options​

ErrorHandlerConfig fields:

OptionDescription
FormatAn ErrorFormat: XML or JSON (see below)
TypePrefixThe value written to the type member
IncludeInstanceInclude the request path in responses
IncludeTimestampAdd a timestamp member to each error
CustomFieldsAdditional members to include in all error responses

Supported Formats​

FormatContent-TypeDescription
ErrorFormatProblemJSONapplication/problem+jsonRFC 7807 JSON format (default)
ErrorFormatProblemXMLapplication/problem+xmlRFC 7807 XML format

Any other value, including ErrorFormatDefault or an empty Format, produces JSON Problem Details too. For Okapi's own ErrorResponse shape, use the default handler instead (WithDefaultErrorHandler).

ProblemDetailErrorHandler(config) returns the handler itself, so it can also be installed per request with c.SetErrorHandler or wrapped in your own ErrorHandler.

Example with XML format:

o.WithProblemDetailErrorHandler(&okapi.ErrorHandlerConfig{
Format: okapi.ErrorFormatProblemXML,
TypePrefix: "about:blank",
IncludeInstance: true,
IncludeTimestamp: true,
})

Response (Content-Type: application/problem+xml):

<ProblemDetail><type>about:blank</type><title>Bad Request</title><status>400</status><detail>Invalid request body</detail><instance>/books</instance></ProblemDetail>

Two things to know about the XML form: the document element is ProblemDetail with no namespace and no XML declaration, and timestamp and CustomFields are not emitted — they are carried as JSON extension members and have no XML representation. Use the JSON format when you need them.

Writing a Problem Detail Directly​

AbortWithProblemDetail sends a ProblemDetail you built yourself, without going through the configured ErrorHandler:

return c.AbortWithProblemDetail(&okapi.ProblemDetail{
Type: "https://api.example.com/errors/out-of-stock",
Title: "Out of stock",
Status: http.StatusConflict,
Detail: "The book is temporarily unavailable",
Instance: c.Path(),
})

NewProblemDetail(code, typeURI, detail) fills Title with the status text and Status with code; chain WithInstance, WithExtension and WithTimestamp to complete it:

problem := okapi.NewProblemDetail(http.StatusTooManyRequests,
"https://api.example.com/errors/rate-limited", "Slow down").
WithInstance(c.Path()).
WithTimestamp().
WithExtension("retry_after", 30)
return c.AbortWithProblemDetail(problem)
{
"type": "https://api.example.com/errors/rate-limited",
"title": "Too Many Requests",
"status": 429,
"detail": "Slow down",
"instance": "/books",
"timestamp": "2026-02-09T21:42:49+01:00",
"retry_after": 30
}

Extensions are marshalled as top-level members next to the standard ones, not under a nested key; an extension with the same name as a standard member replaces it. WithTimestamp adds a timestamp extension in RFC 3339 format. AbortWithProblemDetail always writes JSON, regardless of the handler's Format.