agentleFS
jkanindajkaninda/okapi-skills/error_handling/SKILL.md

error_handling

Skill3 starsChanged 3 months agoMITView on GitHub

Handlers return error. The Abort* helpers write a response through the configured ErrorHandler and return an error you propagate; the Error* helpers write a fixed JSON envelope directly, bypassing the handler. Three formats ship in the box: the default JSON envelope, a fully custom handler, and RFC 7807 Problem Details. Default response body (okapi.ErrorResponse): Always propagate the returned error (return c.AbortX(...)). Writing another body afterwards is a no-op — see "Write-Once Semantics" in the response/ skill. Signature: c.AbortXxx(msg string, err…

2 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Default response body (okapi.ErrorResponse):

    line 17
  2. Very specific:

    Always propagate the returned error (return c.AbortX(...)).

    line 28

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Okapi Error Handling

Handlers return error. The Abort* helpers write a response through the configured ErrorHandler and return an error you propagate; the Error* helpers write a fixed JSON envelope directly, bypassing the handler. Three formats ship in the box: the default JSON envelope, a fully custom handler, and RFC 7807 Problem Details.

Aborting from a Handler

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

Default response body (okapi.ErrorResponse):

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

Always propagate the returned error (return c.AbortX(...)). Writing another body afterwards is a no-op — see "Write-Once Semantics" in the response/ skill.

Abort Methods

Signature: c.AbortXxx(msg string, err ...error) error. All route through the configured error handler.

4xx

MethodStatus
AbortBadRequest400
AbortUnauthorized401
AbortPaymentRequired402
AbortForbidden403
AbortNotFound404
AbortMethodNotAllowed405
AbortNotAcceptable406
AbortProxyAuthRequired407
AbortRequestTimeout408
AbortConflict409
AbortGone410
AbortLengthRequired411
AbortPreconditionFailed412
AbortRequestEntityTooLarge413
AbortRequestURITooLong414
AbortUnsupportedMediaType415
AbortRequestedRangeNotSatisfiable416
AbortExpectationFailed417
AbortTeapot418
AbortMisdirectedRequest421
AbortValidationError422
AbortLocked423
AbortFailedDependency424
AbortTooEarly425
AbortUpgradeRequired426
AbortPreconditionRequired428
AbortTooManyRequests429
AbortRequestHeaderFieldsTooLarge431
AbortUnavailableForLegalReasons451

5xx

MethodStatus
AbortInternalServerError / Abort(err)500
AbortNotImplemented501
AbortBadGateway502
AbortServiceUnavailable503
AbortGatewayTimeout504
AbortHTTPVersionNotSupported505
AbortVariantAlsoNegotiates506
AbortInsufficientStorage507
AbortLoopDetected508
AbortNotExtended510
AbortNetworkAuthenticationRequired511

Generic / special

c.Abort(err) error                                 // 500 from an error
c.AbortWithError(code int, err error) error        // any status, via the error handler
c.AbortWithStatus(code int, message string) error  // any status, default ErrorResponse shape
c.AbortWithJSON(code int, jsonObj any) error       // custom JSON payload
c.AbortWithProblemDetail(p *ProblemDetail) error   // RFC 7807 payload
c.AbortNotModified() error                         // 304, no body (per spec)
c.AbortValidationErrors(errs []ValidationError, msg ...string) error
c.AbortValidationErrorsWithProblemDetail(errs []ValidationError, msg ...string) error

Direct Error Writes (Bypass the Error Handler)

Signature: c.ErrorXxx(message any) error. These write the default JSON envelope verbatim — useful when you deliberately want a fixed shape regardless of the configured handler.

c.Error(code, message)             // basic error with status + message
c.ErrorBadRequest(err)             // 400 — accepts a string, an error, or any value
c.ErrorUnauthorized("no token")    // 401
c.ErrorForbidden(msg)              // 403
c.ErrorNotFound(msg)               // 404
c.ErrorConflict(msg)               // 409
c.ErrorUnprocessableEntity(msg)    // 422
c.ErrorTooManyRequests(msg)        // 429
c.ErrorInternalServerError(msg)    // 500
c.ErrorNotModified()               // 304, no body

The full set mirrors the Abort* table above (ErrorPaymentRequired, ErrorTeapot, ErrorLoopDetected, ErrorNetworkAuthenticationRequired, …).

Custom Error Handler

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

o.WithDefaultErrorHandler() // reset to okapi.DefaultErrorHandler

Per-request override, e.g. from middleware:

func legacyErrors(c *okapi.Context) error {
    if strings.HasPrefix(c.Path(), "/v1/") {
        c.SetErrorHandler(v1ErrorHandler) // overrides the global handler for this request
    }
    return c.Next()
}

RFC 7807 Problem Details

o := okapi.Default()
o.WithSimpleProblemDetailErrorHandler() // application/problem+json, default fields
{
  "type": "about:blank",
  "title": "Bad Request",
  "status": 400,
  "detail": "field Name is required",
  "instance": "/books"
}

Full configuration:

o.WithProblemDetailErrorHandler(&okapi.ErrorHandlerConfig{
    Format:           okapi.ErrorFormatProblemJSON, // or ErrorFormatProblemXML / ErrorFormatDefault
    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",
    },
})

okapi.ProblemDetailErrorHandler(cfg) returns the same handler as a plain ErrorHandler value if you want to compose it yourself.

Format constantContent-Type
okapi.ErrorFormatDefaultapplication/json (standard ErrorResponse)
okapi.ErrorFormatProblemJSONapplication/problem+json
okapi.ErrorFormatProblemXMLapplication/problem+xml

Building a ProblemDetail Manually

detail := okapi.NewProblemDetail(400, "https://example.com/errors/bad-input", "Invalid input").
    WithInstance("/books/123").
    WithExtension("field", "name").
    WithTimestamp()

return c.AbortWithProblemDetail(detail)

ProblemDetail fields: Type, Title, Status, Detail, Instance, plus Extensions (flattened into the JSON object by a custom marshaller).

Structured Validation Errors

return c.AbortValidationErrors([]okapi.ValidationError{
    {Field: "email", Message: "must be a valid email", Value: input.Email},
    {Field: "age",   Message: "must be >= 18"},
}, "validation failed")
{
  "code": 422,
  "message": "validation failed",
  "timestamp": "2026-08-16T21:34:17+01:00",
  "errors": [
    {"field": "email", "message": "must be a valid email", "value": "not-an-email"},
    {"field": "age",   "message": "must be >= 18"}
  ]
}

AbortValidationErrors always uses this ValidationErrorResponse shape, even when a custom error handler is configured — it has a fixed contract. Use AbortValidationErrorsWithProblemDetail for the RFC 7807 equivalent.

Fallback Handlers

o.NoRoute(func(c *okapi.Context) error { return c.AbortNotFound("Custom 404 - Not found") })
o.NoMethod(func(c *okapi.Context) error { return c.AbortMethodNotAllowed("Custom 405") })

Errors from Standard Handlers

A net/http handler registered with HandleStd / HandleHTTP has no *Context and cannot return an error — Okapi cannot capture failures inside it. Write the error response yourself, or convert the route to a native handler.

Status Class Helpers

okapi.IsError(code) bool        // 4xx or 5xx
okapi.IsClientError(code) bool  // 4xx
okapi.IsServerError(code) bool  // 5xx

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.