Error Handling
When something goes wrong in a request, two things must happen: the client gets a correct, safe response, and you get enough information to fix it. PAM handles both at two levels:
- Nimbus catches every exception your routes, middleware and controllers throw. Expected failures (
404,422,403) become Problem Details responses; unexpected ones are logged with their message, file and line, and the client gets a generic500. - The PAM runtime is the safety net under any framework. It catches what escapes the handler, keeps PHP warnings out of response bodies, and recycles a worker whose PHP engine hit a fatal error.
Because workers are persistent, an exception never takes the process down. The request fails, its scope is cleaned up, and the worker serves the next request.
Problem Details
Section titled “Problem Details”Nimbus answers every error with an RFC 9457 application/problem+json body. The code is a stable integer that clients can switch on:
$ curl -i http://127.0.0.1:3000/nothing-hereHTTP/1.1 404 Not Foundcontent-type: application/problem+json; charset=utf-8
{"type":"https:\/\/pam.dev\/problems\/4","title":"Route not found.","status":404,"code":4}code |
Nimbus\Http\ProblemCode |
Typical status |
|---|---|---|
| 1 | ValidationFailed |
422 |
| 2 | Unauthenticated |
401 |
| 3 | Forbidden |
403 |
| 4 | NotFound |
404 |
| 5 | Conflict |
409 |
| 6 | RateLimited |
429 |
| 7 | Timeout |
504 |
| 8 | InternalError |
500 |
| 9 | MethodNotAllowed |
405 |
| 10 | InvalidSignature |
403 |
| 11 | PayloadTooLarge |
413 |
| 12 | UnsupportedMediaType |
415 |
| 13 | CsrfTokenMismatch |
419 |
Validation failures add an errors member; see Validation.
HTTP Exceptions
Section titled “HTTP Exceptions”Throw Nimbus\Http\HttpException from anywhere in a request to stop it with a given status. The arguments are the status, the problem code, the title, and optional extra fields:
use Nimbus\Http\HttpException;use Nimbus\Http\ProblemCode;
public function show(string $id): ProductResource{ $product = $this->products->find((int) $id) ?? throw new HttpException(404, ProblemCode::NotFound, 'Product not found.');
return new ProductResource($product);}Extra fields go in the fourth argument. They are added to the body, but they can never replace type, title, status or code:
throw new HttpException(409, ProblemCode::Conflict, 'Version conflict.', [ 'currentVersion' => 7,]);{"currentVersion":7,"type":"https:\/\/pam.dev\/problems\/5","title":"Version conflict.","status":409,"code":5}To keep the cause for logs and debuggers, pass the original exception as the fifth argument (previous).
Unhandled Exceptions
Section titled “Unhandled Exceptions”Any other exception is an unexpected failure. Nimbus logs it as a JSON line on stderr and answers a generic 500 that never includes the exception message:
$router->get('/boom', function (): never { throw new RuntimeException('Database password is hunter2');});$ curl http://127.0.0.1:3000/boom{"type":"https:\/\/pam.dev\/problems\/8","title":"Internal Server Error","status":500,"code":8}{"timestamp":1796236918878,"level":"error","message":"Unhandled Nimbus exception","context":{"exception":"RuntimeException","message":"Database password is hunter2","file":"/srv/app/routes.php","line":46},"requestId":"standalone-1029282-13","traceparent":"","worker":"standalone"}The requestId ties the log line to the access log entry and to any other line the request wrote. See Logging.
Custom Error Handler
Section titled “Custom Error Handler”Register a handler with onError() to decide yourself how unexpected exceptions are answered, for example to report them to an error tracker. The handler receives the exception and the response, and must return a Response:
use Pam\Http\Response;use Pam\Observability\Telemetry;
$app->onError(function (Throwable $error, Response $response): Response { Telemetry::log('error', 'Request failed', [ 'exception' => $error::class, 'message' => $error->getMessage(), ]);
return $response->json(['message' => 'Something went wrong. We have been notified.'], 500);});$ curl -i http://127.0.0.1:3000/boomHTTP/1.1 500 Internal Server Errorcontent-type: application/json; charset=utf-8
{"message":"Something went wrong. We have been notified."}HttpExceptions (including validation errors and router 404/405) never reach onError(); they are always rendered by the error renderer. When you register a handler, Nimbus no longer logs the exception for you, so log or report it inside the handler.
Custom Error Renderers
Section titled “Custom Error Renderers”The error renderer writes the body of every HttpException, the router’s 404 and 405, and the default 500. Replace it with renderErrorsWith() and any Nimbus\Http\ErrorRenderer:
<?php
declare(strict_types=1);
namespace App\Errors;
use Nimbus\Http\ErrorRenderer;use Nimbus\Http\HttpException;use Pam\Http\Request;use Pam\Http\Response;
final readonly class PlainErrorRenderer implements ErrorRenderer{ public function render(HttpException $error, Request $request, Response $response): Response { return $response->json(['error' => $error->getMessage(), 'code' => $error->problemCode->value], $error->status); }}$app->renderErrorsWith(new App\Errors\PlainErrorRenderer());Laravel-Compatible Errors
Section titled “Laravel-Compatible Errors”If your clients were written against a Laravel API, LaravelErrorRenderer produces Laravel’s JSON error bodies:
use Nimbus\Http\LaravelErrorRenderer;
$app->renderErrorsWith(new LaravelErrorRenderer());$ curl http://127.0.0.1:3000/nothing-here{"message":"Not Found"}$ curl -X POST http://127.0.0.1:3000/api/products -H 'content-type: application/json' -d '{}'{"message":"The name field is required. (and 1 more error)","errors":{"name":["The name field is required."],"price":["The price field is required."]}}Unhandled exceptions answer {"message": "Server Error"}, as Laravel does with APP_DEBUG=false.
Reporting to Sentry
Section titled “Reporting to Sentry”Nimbus\Sentry\SentryReporter reports failures that become 5xx responses to Sentry. It is a request lifecycle observer built for persistent workers: it restores Sentry’s global scope between requests, so breadcrumbs and user data of one request never leak into the report of the next. Query strings, bodies, cookies and headers are never sent.
pam composer require sentry/sentryuse Nimbus\Sentry\SentryReporter;
if ($reporter = SentryReporter::fromEnvironment($app->container())) { $app->observe($reporter);}fromEnvironment() reads SENTRY_DSN, SENTRY_ENVIRONMENT (or APP_ENV) and SENTRY_RELEASE, and returns null when the package or the DSN is missing.
Runtime Behavior
Section titled “Runtime Behavior”These rules apply to every PAM application, with or without Nimbus:
- Uncaught exceptions that escape the handler are logged by the runtime (
"Unhandled request exception") and answered with500and the body{"error":"Internal Server Error","message":"The request failed. Use the request ID to inspect server logs."}. exposeErrorsis a listener option for development. Whentrue, the runtime’s500body carries the exception message, and PHP’sdisplay_errorsis left as configured. Nimbus never exposes messages, whatever this option says.- PHP warnings and notices never reach response bodies in server mode: PAM sets
display_errors=0andlog_errors=1unlessexposeErrorsis set, andexpose_phpis off by default. - Fatal errors, exceeding
memory_limit, andexit()abort the PHP engine. PAM answers that request with the generic500, logsphp_engine_failed, and retires the worker. Underpam startthe supervisor replaces it with a fresh worker;pam devwaits for the next file change. - Client disconnects cancel the request Fiber. The request is recorded with status
499and is not logged as an application error. - Request deadlines: a request that runs past
requestTimeoutMsgets504and its worker is recycled.
$app->listen(3000, '127.0.0.1', [ 'exposeErrors' => getenv('APP_ENV') === 'local',]);Testing Errors
Section titled “Testing Errors”The in-memory test client has an assertion for every common error status:
public function test_unknown_products_are_not_found(): void{ $this->getJson('/api/products/999') ->assertNotFound() ->assertJsonPath('code', 4);}
public function test_admin_routes_need_a_key(): void{ $this->getJson('/api/admin/stats')->assertUnauthorized();}Other assertions include assertForbidden(), assertUnprocessableEntity() and assertStatus($code).