stable.se

API-tokens och webhooks ingår inte i de planer vi säljer idag. Hör av dig innan du bygger på API:et.

Utvecklardokumentationen är för närvarande bara tillgänglig på engelska.

Error Handling

Understand API error responses, error codes, and best practices for handling errors.

4 min read

Response Format

Success response shapes are endpoint-specific: some endpoints return the resource directly, others wrap it in an envelope with the result in data (see Getting Started). Errors share one shape.

Error Response

Errors use a flat envelope: the machine-readable code, a human-readable message, the human-readable status string, and — for some errors — a detail object with extra context.

{
  "status": "404 Not Found",
  "message": "Horse not found",
  "code": "not_found"
}

HTTP Status Codes

StatusMeaningWhen It Happens
200 OKSuccessRequest succeeded
201 CreatedCreatedResource successfully created
204 No ContentDeletedDeletion or action succeeded (no body)
400 Bad RequestInvalid inputMalformed request, validation errors
401 UnauthorizedAuth requiredMissing or invalid authentication
402 Payment RequiredUpgrade requiredPlan or quota does not allow the action
403 ForbiddenNo accessInsufficient permissions/scopes or disabled module
404 Not FoundMissingResource doesn't exist or you don't have access
409 ConflictConflictResource already exists or state conflict
429 Too Many RequestsRate limitedRate limit exceeded
500 Internal Server ErrorServer errorSomething went wrong on our end

Error Codes

The code field is a machine-readable classification. A 401 for an unknown, expired or revoked token uses UNAUTHORIZED with a reason such as token_invalid or session_expired, so compare codes without regard to case. Some errors also carry data and error fields; rely on the HTTP status and code.

CodeDescription
bad_requestMalformed request or invalid parameters
unauthorizedAuthentication required or token invalid
forbiddenInsufficient permissions for this operation
not_foundRequested resource not found
conflictDuplicate or conflicting resource state
validation_failedOne or more input fields failed validation
too_many_requestsRate limit exceeded; slow down
internal_errorUnexpected server error
module_not_enabledModule is not enabled (403)
upgrade_requiredPlan or quota does not allow this action (402)

Validation Errors

When input validation fails (HTTP 400), the response includes field-level error details in the errors object:

{
  "status": "400 Bad Request",
  "message": "Validation failed",
  "errors": {
    "name": [
      { "code": "length", "message": "Must be between 1 and 255 characters", "params": { "min": 1, "max": 255 } }
    ],
    "email": [
      { "code": "email", "message": "Invalid email format" }
    ]
  },
  "form_errors": [],
  "code": "validation_failed"
}

Field Structure

  • errors -- an object keyed by field name, each containing an array of error objects
  • form_errors -- an array of form-level (non-field-specific) errors
  • Each error has code (machine-readable), message (human-readable), and optional params

Conflict Errors with Field Targeting

Some 409 Conflict responses also include field-level errors:

{
  "status": "409 Conflict",
  "message": "This email is already registered",
  "errors": {
    "email": [
      { "code": "conflict", "message": "This email is already registered" }
    ]
  },
  "form_errors": [],
  "code": "conflict"
}

Handling Validation Errors

Map field errors to your form inputs:

const response = await fetch('https://api.stable.se/v1/horses', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: '', breed: 'Warmblood' }),
});

if (!response.ok) {
  const body = await response.json();

  if (body.code === 'validation_failed' && body.errors) {
    // Field-level errors
    for (const [field, fieldErrors] of Object.entries(body.errors)) {
      for (const error of fieldErrors) {
        console.log(`${field}: ${error.message}`);
      }
    }
  }

  if (body.form_errors?.length > 0) {
    // Form-level errors (not tied to a specific field)
    for (const error of body.form_errors) {
      console.log(`Form error: ${error.message}`);
    }
  }
}

Rate Limit Errors

When you exceed the rate limit, you'll receive a 429 response with headers indicating when you can retry:

HTTP/1.1 429 Too Many Requests
X-RateLimit-Scope: api-token
Retry-After: 45
Content-Type: application/json

See the Rate Limits guide for details on limits and backoff strategies.

Best Practices

  • Always check the HTTP status code before parsing the response body
  • Use the code field for programmatic error handling, not the message (which may change)
  • Handle 429 gracefully with exponential backoff based on Retry-After
  • Don't expose raw API errors to end users -- map them to user-friendly messages
  • Log the full response for 5xx errors to help with debugging
  • Retry reads with bounded backoff when appropriate; retry mutations only when their idempotency contract permits it
  • Don't retry 4xx errors without fixing the request -- they indicate a client issue