Skip to main content

API Error Patterns

Stable API error contract

When building ZeyOS services that expose APIs, establish a consistent response envelope that clients can rely on. Every endpoint should return the same top-level structure regardless of whether the operation succeeded or failed. This reduces client-side complexity and makes services easier to monitor and debug.

Success response:

JSON
{
"result": 1,
"data": { ... }
}

Error response:

JSON
{
"error": "Human-readable error message",
"details": "Technical details for debugging"
}

Implementation pattern

XML
<array var="RES" />

<try>
<!-- Business logic here -->
<set var="RES.result">1</set>

<catch var="err">
<set var="RES.error">Operation failed</set>
<set var="RES.details">$err</set>
</catch>
</try>

<header>Content-Type: application/json</header>
<output><encode:json var="RES" /></output>

This pattern ensures that:

  • The client always receives valid JSON, never a raw error dump
  • The top-level key (result vs. error) immediately signals success or failure
  • Technical error details are available for debugging without leaking sensitive internals
  • The HTTP Content-Type header is always set correctly, even on error

HTTP status codes

Use the status attribute of the <header> command to set appropriate HTTP status codes in error scenarios:

XML
<catch var="err">
<header status="400" />
<set var="RES.error">Bad request: $err</set>
</catch>

Common status codes for API services:

CodeMeaningWhen to use
200OKSuccessful operations (default)
201CreatedSuccessful resource creation
400Bad RequestInvalid input, malformed JSON, missing required fields
401UnauthorizedMissing or invalid authentication
403ForbiddenAuthenticated but insufficient permissions
404Not FoundRequested resource does not exist
500Internal Server ErrorUnexpected failures, database errors