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.
Recommended response shapes
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 (
resultvs.error) immediately signals success or failure - Technical error details are available for debugging without leaking sensitive internals
- The HTTP
Content-Typeheader 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:
| Code | Meaning | When to use |
|---|---|---|
200 | OK | Successful operations (default) |
201 | Created | Successful resource creation |
400 | Bad Request | Invalid input, malformed JSON, missing required fields |
401 | Unauthorized | Missing or invalid authentication |
403 | Forbidden | Authenticated but insufficient permissions |
404 | Not Found | Requested resource does not exist |
500 | Internal Server Error | Unexpected failures, database errors |