Skip to content

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 generic 500.
  • 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.

Nimbus answers every error with an RFC 9457 application/problem+json body. The code is a stable integer that clients can switch on:

Terminal window
$ curl -i http://127.0.0.1:3000/nothing-here
HTTP/1.1 404 Not Found
content-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.

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).

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');
});
Terminal window
$ 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.

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:

bootstrap/app.php
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);
});
Terminal window
$ curl -i http://127.0.0.1:3000/boom
HTTP/1.1 500 Internal Server Error
content-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.

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:

app/Errors/PlainErrorRenderer.php
<?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);
}
}
bootstrap/app.php
$app->renderErrorsWith(new App\Errors\PlainErrorRenderer());

If your clients were written against a Laravel API, LaravelErrorRenderer produces Laravel’s JSON error bodies:

bootstrap/app.php
use Nimbus\Http\LaravelErrorRenderer;
$app->renderErrorsWith(new LaravelErrorRenderer());
Terminal window
$ 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.

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.

Terminal window
pam composer require sentry/sentry
bootstrap/app.php
use 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.

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 with 500 and the body {"error":"Internal Server Error","message":"The request failed. Use the request ID to inspect server logs."}.
  • exposeErrors is a listener option for development. When true, the runtime’s 500 body carries the exception message, and PHP’s display_errors is 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=0 and log_errors=1 unless exposeErrors is set, and expose_php is off by default.
  • Fatal errors, exceeding memory_limit, and exit() abort the PHP engine. PAM answers that request with the generic 500, logs php_engine_failed, and retires the worker. Under pam start the supervisor replaces it with a fresh worker; pam dev waits for the next file change.
  • Client disconnects cancel the request Fiber. The request is recorded with status 499 and is not logged as an application error.
  • Request deadlines: a request that runs past requestTimeoutMs gets 504 and its worker is recycled.
index.php
$app->listen(3000, '127.0.0.1', [
'exposeErrors' => getenv('APP_ENV') === 'local',
]);

The in-memory test client has an assertion for every common error status:

tests/ProductTest.php
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).