Errors
The Go SDK uses two standard-library patterns.
- Anything declared as
var ErrXxx = errors.New(...)is a sentinel. Test for it witherrors.Is(err, pkg.ErrXxx). - Anything declared as a type (
type FooError struct{...}) is a typed error. Pull it out witherrors.As(err, &target)when you need its fields.
The list below is every exported sentinel and typed error, by package.
client
Section titled “client”The platform client returns a typed *client.APIError for every non-2xx response. There are no
sentinels: branch on the status code.
err := c.Principals().Update(ctx, id, &req)var apiErr *client.APIErrorif errors.As(err, &apiErr) { switch apiErr.StatusCode { case http.StatusNotFound: // not found case http.StatusConflict: // conflict default: // apiErr.Code() and apiErr.Message() are the platform's structured error }}| Member | Meaning |
|---|---|
StatusCode, Body |
The status and the raw response body. |
Code() |
The platform error code, from the body’s error (or the legacy code) member. Empty when the body is not a structured envelope. |
Message() |
The platform message, from message or the OAuth error_description. |
IsNotFound(), IsConflict(), IsUnauthorized(), IsForbidden() |
404, 409, 401, 403. |
Retryable() |
True for 408, 425, 429, 500, 502, 503 and 504. This says what the status means, not that the client retried: it retries only as the retry rule allows, and a non-repeatable request is not retried on 500, 502, 503 or 504. |
A success status never produces an error. Routes that answer 204 No Content return only an error,
nil on success, so there is no body to decode. Other errors the client returns are ordinary wrapped
errors: *client.OutcomeUnknownError when a request that is not repeatable (a plain POST) got a 502, 503 or 504, or failed in transport after it may have been sent, and was not sent again (Method, URL, StatusCode, Body and Err; Unwrap yields the *APIError or the transport error; test with client.IsOutcomeUnknown), http: ... for a transport failure that outlasted the retries, token provider: ... when
your token function failed, marshal body: ..., decode response: ..., and
client.ErrInvalidOnBehalfOf for a bad on-behalf-of value.
usecase and usecaseop
Section titled “usecase and usecaseop”Domain operations return *usecase.Error. Its Kind selects the HTTP status through HTTPStatus().
Build one in an operation’s Validate, Authorize or Execute with usecase.Validation,
BusinessRule, Authorization, NotFound, Conflict or Internal.
event, err := usecaseop.Run(ctx, uow, PlaceOrder(repo), cmd, ec)if err != nil { if ue := usecase.AsError(err); ue != nil { http.Error(w, ue.Message, ue.HTTPStatus()) return } http.Error(w, "internal", http.StatusInternalServerError) return}usecaseop.Run returns an operation’s own errors unchanged, and wraps a failed commit (repository,
event or audit write) as an Internal one. The lower-level usecasepgx.Commit* functions return a
sealed usecase.Result[E]; usecase.Into(result) turns it into (E, error).
| Kind | Status | Typical code |
|---|---|---|
validation |
400 | Your own, such as TOTAL_INVALID |
authorization |
403 | Your own |
not_found |
404 | Your own |
business_rule, conflict |
409 | Your own |
internal |
500 | USECASE_MISCONFIGURED, USECASE_NIL_PLAN, TX_BEGIN, TX_COMMIT, PERSIST, DELETE, EVENT_WRITE, DISPATCH_JOB_WRITE, AUDIT_WRITE, DISPATCH_JOB_INVALID, DISPATCH_JOB_UNSUPPORTED |
Error has Kind, Code, Message, Details and Cause, and it unwraps to the cause, so
errors.Is finds a driver error underneath.
A single typed *auth.Error, with a Kind. The sentinels exist so you can match a kind with
errors.Is without caring about the message.
| Sentinel | Meaning |
|---|---|
auth.ErrTokenExpired |
The JWT’s exp has passed. Refresh and retry. |
auth.ErrInvalidToken |
Bad signature, issuer, audience or format; also a token_use that is not an API credential. Reject. |
auth.ErrDiscovery |
OIDC discovery or the JWKS fetch failed: network or DNS. |
auth.ErrTokenExchange |
/oauth/token or a related endpoint failed. |
auth.ErrConfig |
Bad configuration, such as a missing required field. |
auth.ErrCrypto |
A cryptographic operation failed. |
ac, err := validator.ValidateBearer(r.Context(), r.Header.Get("Authorization"))switch {case errors.Is(err, auth.ErrTokenExpired): http.Error(w, "token expired", http.StatusUnauthorized)case errors.Is(err, auth.ErrInvalidToken): http.Error(w, "invalid token", http.StatusUnauthorized)case err != nil: http.Error(w, "auth error", http.StatusInternalServerError)}_ = acauth has no ErrBackend; its network failures are ErrDiscovery or ErrTokenExchange.
Field tokens fail with *auth.FieldError, whose Reason is one of the auth.FieldReason* strings
(malformed, wrong_typ, wrong_token_use, wrong_aud, expired, invalid_token, pcr,
missing_proof, invalid_proof, jkt_mismatch, htm_mismatch, htu_mismatch, ath_mismatch,
stale_proof). A *FieldError also matches auth.ErrInvalidToken. A key-fetch failure is
ErrDiscovery, not a FieldError, which is how FieldMiddleware tells a 401 from a 503.
webhook
Section titled “webhook”Two equivalent APIs, with their own sentinels. See Webhooks.
Verifier sentinel |
|
|---|---|
ErrMissingSignature, ErrMissingTimestamp, ErrBadTimestamp, ErrStaleTimestamp, ErrBadSignature |
Header missing, header unparseable, outside the skew, signature mismatch. |
Validator sentinel |
Suggested status |
|---|---|
ErrValidatorMissingSignature, ErrValidatorMissingTimestamp, ErrValidatorInvalidTimestamp |
400 |
ErrTimestampExpired, ErrTimestampInFuture |
401 |
ErrValidatorInvalidSignature |
403 |
ErrMissingSecret |
500: your configuration is wrong |
ErrTimestampExpired can arrive wrapped with the tolerance in the message, so use errors.Is.
| Error | Meaning |
|---|---|
cache.ErrInvalidTTL |
A zero or negative TTL passed to SetBytes. |
cache.ErrBackend |
A driver-level I/O failure. Wrapped, so errors.Is works. |
*cache.SerializeError |
Set or GetOrSet could not marshal the value. |
*cache.DeserializeError |
Get or GetOrSet could not unmarshal the stored bytes into T, for example after a schema change. |
v, ok, err := cache.Get[User](ctx, c, "u:1")var de *cache.DeserializeErrorswitch {case errors.As(err, &de): // the stored bytes do not match Tcase errors.Is(err, cache.ErrBackend): // network or database hiccup; usually retryable}_, _ = v, ok| Error | Meaning |
|---|---|
lock.ErrInvalidTTL |
A zero or negative TTL passed to Acquire. |
lock.ErrBackend |
A driver-level I/O failure. |
Acquire returns (nil, nil) when the key is held by someone else. That is not an error; the error
path is reserved for backend faults.
scheduledjobs
Section titled “scheduledjobs”Runner.Process never returns an error. It returns a Result{Kind, Message} for you to map to an HTTP
status. Failures that happen in the background reach the OnError hook as a *scheduledjobs.RunnerError
whose Kind is ErrCallbackFailed, ErrLockFailed or ErrHandlerPanicked. See
Scheduled jobs.
outbox, outboxpgx, outboxsql
Section titled “outbox, outboxpgx, outboxsql”There are no sentinels. The writers return:
- a plain
errorfrom building a row, before anything is written: a dispatch job that breaks the batch endpoint’s rules (DispatchJob.Validate), an event with no id or type, an event whoseToDataJSONfails or returns invalid JSON, a command that cannot be serialised for its audit row, or an invalid table name; - the driver’s error from the
INSERT, unwrapped; - for a push, a
*outbox.PushErrorwhoseCodeisTOPIC_INVALID,TYPE_INVALID,TYPE_RESERVED,DATA_INVALID,DATA_NOT_OBJECT,DATA_TOO_LARGE,PUSH_ID_INVALIDorCLIENT_INVALID.
Inside usecaseop.Run and usecasepgx.Commit*, row-building and INSERT failures surface as
usecase.Internal errors (EVENT_WRITE, DISPATCH_JOB_WRITE, AUDIT_WRITE) wrapping the cause, and
the transaction rolls back. Dispatch jobs on a plan are checked before the transaction opens, so these
write nothing:
| Code | Kind | When |
|---|---|---|
DISPATCH_JOB_INVALID |
internal |
A job breaks a rule. Message is the rule’s text exactly as DispatchJob.Validate returns it, and Details["index"] is the job’s position. |
DISPATCH_JOB_UNSUPPORTED |
internal |
The unit of work’s sink is not a usecasepgx.DispatchJobSink. |
Check job values that come from the command in your operation’s Validate, so the caller gets a
validation error (400) rather than internal.
Synchronizer.Sync never returns an error. Per-category failures are on the returned *sync.Result
(HasErrors(), Errors()). Subscriptions are not sent when the connections sync failed, and the
subscriptions result says so. SkippedRoles and PasswordHashIgnored on the principals result are
not errors: the sync applied, and those names or hashes were left out.
r := sync.NewSynchronizer(c).Sync(ctx, set, sync.DefaultOptions())if r.HasErrors() { for category, msg := range r.Errors() { log.Printf("sync category %s failed: %s", category, msg) }}