Error handling
About 2292 wordsAbout 8 min
Overview
Spora uses a consistent JSON error envelope across all API endpoints and a toast-based notification system on the frontend. The backend is the single source of truth for error codes; the frontend maps them to severity levels and display strategies.
Backend Error Format
All API error responses follow this envelope:
{
"error": {
"code": "MACHINE_CODE",
"message": "Human-readable description."
}
}| Field | Type | Description |
|---|---|---|
code | string | Machine-readable identifier. Deterministic — the frontend can use this to route error handling. |
message | string | User-safe message. Shown as-is in toasts. May contain technical detail in development mode. |
Note: Rate-limited responses carry the retry interval via the standard Retry-After HTTP response header, not as a JSON body field (app/Http/AuthController.php:421). The retryAfter and action fields shown in earlier drafts are not part of the current envelope.
Error Code Registry
Codes below are returned by controllers, with two exceptions: LLM_PROVIDER_ERROR and LLM_RATE_LIMIT are never written by the backend — neither by a controller nor by the task classifier. They exist only as cases in frontend/src/utils/errorMapper.ts:55-57, a module the app does not call, and are reserved.
The codes the agent loop and the workers write into tasks.error_code are a registry of their own — see Task error codes.
| Code | HTTP Status | Severity | Description |
|---|---|---|---|
VALIDATION_ERROR | 422 | warning | Form input failed server-side validation. The agent’s step cap is refused with this code: a max_steps outside 1..SPORA_MAX_STEPS — the instance’s ceiling, 200 by default — answers max_steps must be between 1 and N., and a value that is not a whole number answers max_steps must be an integer between 1 and N.. The same bounds apply to the LLM’s create_agent / update_agent; on the agent template format the refusal is the MAX_STEPS_RANGE template error, and the import answers 422 with the code in error.details. |
INVALID_EFFORT | 422 | warning | The effort field of a task or chat body is neither a string nor null — a null is read as an omitted field, not as a bad one. TaskEffortRequestValidator::parse() answers it (app/Http/TaskEffortRequestValidator.php), with one message. |
EFFORT_LEVEL_UNSUPPORTED | 422 | warning | The effort is a level the agent’s LLM configuration does not offer, or the agent has no LLM configuration at all. EffortService::assertLevel() answers it (app/Services/EffortService.php) with four messages, one per reason. The API reference lists them. |
NOT_UNIQUE | 422 | warning | A media-folder uniqueness rule was broken — two siblings with one name, or one filename twice in the same folder. The media-folder service owns both rules and answers before the unique index does. |
FOLDER_FILENAME_TAKEN | 422 | warning | The media folder already holds a file with that name. |
INVALID_JSON | 400 | warning | Malformed request body. |
BAD_REQUEST | 400 | warning | Malformed path parameter (app/Core/Router.php:64). |
INVALID_KIND | 400 | warning | A media_assets.kind outside the vocabulary (asset, template, example) was sent to the upload endpoint. The mark is advisory, but the column cannot hold a value the filter could never select. |
UNAUTHENTICATED | 401 | error | No valid session. Frontend shows expiry toast and routes to /login. |
INVALID_CREDENTIALS | 401 | error | Login failed — wrong email or password (app/Http/AuthController.php:106). |
WRONG_PASSWORD | 401 | error | Current-password check failed during a password change (app/Http/AuthController.php:194). |
INVALID_PASSWORD | 422 | error | New password does not meet the policy (app/Http/AuthController.php:192). |
ACCOUNT_UNVERIFIED | 403 | error | Account email not verified. |
EMAIL_NOT_VERIFIED | 403 | error | Must verify current email before changing it (app/Http/AuthController.php:357). |
REGISTRATION_DISABLED | 403 | error | Public registration is disabled. |
FORBIDDEN | 403 | error | User lacks permission for this resource. |
NOT_FOUND | 404 | warning | Resource does not exist or is not visible to this user. |
AGENT_NOT_FOUND | 404 | warning | The agent is missing, or the caller may not see it. |
METHOD_NOT_ALLOWED | 405 | warning | The path is mounted for other methods but not this one. Raised by app/Core/Router.php — the mint route answers this while its scope’s toggle is off, because the path stays mounted for listing and revoking. |
NOT_CONFIGURED | 503 | warning | Subsystem not configured (e.g. SSE; app/Http/SseController.php:55). |
EMAIL_TAKEN | 409 | warning | Registration or email-change attempted with an existing email. |
INVALID_STATE | 409 | warning | Operation invalid in current state (e.g., approve non-pending task). |
GROUP_HAS_MEDIA_FOLDERS | 409 | warning | The group still owns media folders. media_folders.principal_id is ON DELETE RESTRICT, so the folders have to go first. Distinct from GROUP_HAS_AGENTS because the agent-transfer endpoint cannot re-target a folder. |
INVALID_TOKEN | 400 | warning | Confirmation / reset selector-token pair is invalid. |
TOKEN_EXPIRED | 400 | warning | Confirmation / reset token has expired. |
RESET_DISABLED | 403 | warning | Password reset is disabled in this build. |
TOO_MANY_REQUESTS | 429 | warning | Auth endpoint rate limit hit. Check the Retry-After header. |
CSRF_TOKEN_MISSING | 403 | warning | Required X-CSRF-Token header missing on a state-changing request. |
CSRF_INVALID | 403 | warning | CSRF token did not match the session value. |
AUTH_ERROR | 500 | error | Unspecified auth library failure (catch-all). |
TOOLS_RECOMMENDS_SKILLS_MISSING | 500 | error | One or more #[Tool(recommendsSkills: ...)] entries do not resolve on disk under any scanner root. Strict-mode — no env-flag opt-out. error.details.violations[] carries the offenders as { tool_class, tool_name, missing[] }. See Concepts → Tool system → /api/v1/tools errors. |
LLM_PROVIDER_ERROR | — | warning | Reserved. The backend never writes it; it exists only as a case in errorMapper.ts. |
LLM_RATE_LIMIT | — | warning | Reserved. The backend never writes it; it exists only as a case in errorMapper.ts. |
DECRYPTION_FAILED | 422 | error | Stored settings could not be decrypted (key mismatch or corruption). |
INTERNAL_SERVER_ERROR | 500 | error | Unexpected server failure. Technical detail shown in development mode only. |
The endpoint that names a configuration’s levels is on every surface.GET /api/v1/agents/{id}/effort takes the session cookie, and each bearer-key surface has its own: GET /api/v1/agent-api/effort, GET /api/v1/group-api/agents/{agentId}/effort and GET /api/v1/global-api/agents/{agentId}/effort. A caller on any of them can read the levels before sending one, so a level the endpoint does not list is one the caller should never send.
HTTP Success Envelope
Successful responses wrap data in a data key:
{
"data": { ... }
}Task error codes
A failed task carries its reason in tasks.error_code, and those codes are written by the agent loop and the workers — never by a controller. They are a registry of their own: BAD_REQUEST and AUTH_ERROR appear in the HTTP registry above as well, and mean different things in each. Whether a failed run is retried depends on the code, so the table says which ones qualify.
| Code | Retryable | Written by | Description |
|---|---|---|---|
RATE_LIMIT | yes | ErrorClassifier | The provider is rate-limiting the run. |
SERVER_OVERLOADED | yes | ErrorClassifier | The provider answered 529. |
SERVER_ERROR | yes | ErrorClassifier | The provider answered 500 or 520. |
GATEWAY_ERROR | yes | ErrorClassifier | The provider could not be reached at all — DNS failure, reset connection, refused TLS handshake — or answered with a retryable error that is not a 5xx. |
AUTH_ERROR | yes | ErrorClassifier | The provider answered 401 or 403. |
LLM_TIMEOUT | yes | ErrorClassifier | The request timed out. |
WORKER_DISCONNECTED | yes | WorkerReaper | The worker running the task vanished — the browser’s SharedWorker in client-worker mode, the server worker otherwise. The reaper arms the agent’s configured automatic retry for it in server-worker mode only; an agent without a retry policy leaves the row FAILED for the operator (worker deployment). |
ORPHANED | yes | — | The former name of WORKER_DISCONNECTED. No code path writes it any more; it is kept for historical rows. |
BAD_REQUEST | no | ErrorClassifier | The provider refused the request — it answered 400. |
TOOL_ERROR | no | — | Reserved. The classifier holds a friendly message for it, but no code path writes it into tasks.error_code. |
NO_LLM_CONFIGURATION | no | ErrorClassifier | The agent has no LLM configuration. |
USAGE_LIMIT_REACHED | no | TickPhaseRunner | A hard usage decision stopped the run. A retry would spend the very budget the decision refused, so it is terminal by design. |
CONTEXT_WINDOW_FIRST_TURN | no | ContextWindowRecovery | The context window is too small even for the first turn. |
REJECT_FAILED | no | Orchestrator | Rejecting an approval failed. |
RESUME_FAILED | no | ApprovedBatchExecutor | Resuming an approved batch failed. |
UNKNOWN | no | ErrorClassifier, WorkerQueueProcessor, ScheduledRunProcessor | The exception did not classify. |
The retryable set is the core’s, and the core’s list is the authority.ErrorClassifier::RETRYABLE_ERROR_CODES and RetryScheduler::RETRYABLE_ERROR_CODES are the same list — the classifier accepts a code and the scheduler accepts a code, and neither knows about the other. The admin UI mirrors that list to decide whether to offer a retry at all. It promises an automatic retry only when the task payload carries a retry_after timestamp, and that key is always present on the task resource — null when no retry is scheduled.
Backend Exception Handling
app/Core/Kernel.php owns global exception handling via Kernel::handleException() (app/Core/Kernel.php:101-157).
Development Mode
When app_env is development or local (app/Core/Kernel.php:126), the error response includes a debug object:
{
"error": {
"code": "INTERNAL_SERVER_ERROR",
"message": "An unexpected error occurred."
},
"debug": {
"exception": "ClassName",
"message": "Original message",
"file": "/path/to/file.php",
"line": 42
}
}Production Mode
No stack traces, no file paths. The message is a generic fallback for 5xx errors.
Frontend Architecture
Severity Levels
| Level | Style | Auto-dismiss |
|---|---|---|
error | Red, alert icon | No — persistent until user dismisses |
warning | Amber, warning icon | 8 seconds |
success | Green, check icon | 4 seconds |
info | Blue, info icon | 4 seconds |
HTTP Status → Severity Mapping
Implemented in frontend/src/utils/errorMapper.ts:15-48:
| HTTP Status Range | Severity |
|---|---|
| 200–299 | (success — no error display) |
| 400–499 (except 401, 403, 404, 429) | warning |
| 401 | error → redirect to /login |
| 403 | error |
| 404 | warning |
| 429 | warning |
| 500+ | error |
Toast Notification System
File Structure
frontend/src/
├── components/ui/
│ ├── Toast.vue # Single toast: icon, message, dismiss button, progress bar
│ └── ToastContainer.vue # Portal-mounted queue, bottom-right (desktop) / top-center (mobile)
├── composables/
│ └── useToast.ts # toast.success / warning / error / info(message, opts?)
└── utils/
└── errorMapper.ts # HTTP status → { severity, code, action }Toast.vue Props
| Prop | Type | Description |
|---|---|---|
id | string | Unique identifier (used by container to track dismissals) |
severity | 'error' | 'warning' | 'success' | 'info' | Controls icon, color, auto-dismiss |
message | string | Primary text content |
action | string? | Optional button label (e.g., "Retry", "Login") |
onAction | (() => void)? | Callback when action button is clicked |
onDismiss | () => void | Remove this toast from the queue |
useToast.ts API
const toast = useToast()
toast.success('Agent saved successfully.')
toast.warning('Validation failed. Check your input.')
toast.error('Session expired. Please log in again.', { action: 'login' })ToastOptions (frontend/src/composables/useToast.ts:17-21) accepts action, onAction, and retryAfter. The retryAfter field is currently stored on the toast item but is not consumed by Toast.vue (auto-dismiss is severity-based, not time-relative); the value is available for future UI work.
Global Error Handler
Session-expiry handling is registered in frontend/src/App.vue:26-49 via setupSessionHandler (set up in frontend/src/api/client.ts:21-23). When the API client sees a 401 with code: "UNAUTHENTICATED" on a request made while the user is logged in, it invokes the registered handler, which shows a toast and either lets the user click an action button or auto-redirects after 3 seconds. main.ts does not register a app.config.errorHandler — uncaught Vue errors fall through to the browser console.
Error Display Strategies
Strategy 1: Inline (Existing Pattern)
For form validation errors on the same page as the form. No toast — error appears next to the relevant field.
Used by: Login, Register, Agent creation/edit, LLM Config creation/edit.
<p role="alert" class="text-sm text-destructive">{{ error }}</p>Strategy 2: Toast
For operations triggered by buttons, async polling, or background actions where no form field is directly tied to the error.
Used by: Task approve/reject failures, agent deletion, LLM config set-default, and 401 session-expiry. Uncaught Vue runtime errors currently fall through to the browser console (see “Global Error Handler” above).
Strategy 3: Inline + Toast
When both the field and a broader context matter. Validation errors on a form also show a toast with the summary.
Used by: None currently — reserved for future use if complexity grows.
Strategy 4: Redirect
Only for UNAUTHENTICATED (401). The router guard on authStore (frontend/src/router/index.ts:161-175) redirects unauthenticated visitors to /login. The attempted URL is not currently passed through as a ?redirect= query parameter — that round-trip is on the roadmap. The 401 session-expiry flow is handled separately by App.vue:26-49, which redirects after the user dismisses the toast (or after 3 s).
Existing Patterns to Preserve
- Store-level errors: thrown from store actions, caught by calling pages, displayed inline. Stores do NOT show toasts — they propagate.
- Polling errors (tasks.ts): silently swallowed in polling loops (no toast for stale polls). Only surfaced on user-initiated actions.
- Auth store (auth.ts):
init()silently handles “no session” as non-error (frontend/src/stores/auth.ts:42-50).logout()is optimistic — errors swallowed via.catch(() => {})(frontend/src/stores/auth.ts:83).
Backend Changes
app/Core/Kernel.php— addretryAfterandactionfields to rate-limit error responses.- Add
LLMProviderErrorandLLMRateLimitexception classes that carry structured context from driver responses. - Add
DECRYPTION_FAILEDcode toDecryptionFailedExceptionhandler.
Frontend Changes
- Create
Toast.vuecomponent. - Create
ToastContainer.vue(teleport to<body>, manages queue). - Create
useToast.tscomposable. - Create
errorMapper.tsutility. - Register global error handler in
main.ts. - Update
api/client.tsto dispatch toasts on non-2xx responses (opt-in per call viaoptions.showToast). - Update
stores/auth.tsto show toast + redirect on 401.
Implementation Status (Audit)
The “Backend Changes” and “Frontend Changes” sections above were an early design plan. Most items are now implemented:
Toast.vue,ToastContainer.vue,useToast.ts,errorMapper.tsexist (frontend/src/components/ui/,frontend/src/composables/useToast.ts,frontend/src/utils/errorMapper.ts).LLMProviderExceptionandLLMRateLimitExceptionexist (app/Drivers/Exceptions/).- Session expiry is handled in
App.vue(notmain.ts). api/client.tsdoes not implement anoptions.showToastflag — the API client throwsApiErroron non-2xx, and the calling code decides whether to surface it as a toast.
Out of Scope
- Error deduplication (future, only if rapid duplicate errors become a problem)
- Error logging service integration (handled by PSR-3 Monolog already — see Logging)
- Field-level validation error mapping (server returns flat
message; inline pattern is sufficient for current forms)