Blunder handles PHP errors and uncaught exceptions in web applications and command-line tools. Use detailed reports during development, generic responses in production, or an output-free handler for logging and capture.
Blunder requires PHP 8.2 or newer. Detailed XML reports use PHP’s SimpleXML extension.
composer require maplephp/blunderSee the 2.0 upgrade guide and changelog. Save each PHP example as a separate file beside your application's Composer vendor/ directory.
Register Blunder early in your entry point. This example starts in production mode. Run it from a terminal to see a generic error message and exit status 1.
<?php
use MaplePHP\Blunder\Run;
require __DIR__ . '/vendor/autoload.php';
$run = Run::auto();
if (in_array(PHP_SAPI, ['cli', 'phpdbg'], true)) {
$run->setExitCode(1);
}
$run->register();
throw new RuntimeException('Sample failure');On CLI and phpdbg, automatic handling selects the CLI formatter. On the web it negotiates the request’s Accept header. HTML is the default when the header is absent. It also supports plain text, JSON, JSON:API and XML. Negotiated web responses include Vary: Accept. A request that accepts none of the supported types receives an empty 406 response.
Use Run::auto(production: false) on a trusted development system. An explicitly constructed run, such as new Run(new HtmlHandler()), starts with detailed output. Call production() on that run to make its reports generic. Production skips source reads, request context, solution providers, editor links and debug tables. Trusted listeners still receive the original exception.
For production, configure PHP at startup so native diagnostics also stay out of responses. This covers errors that happen before registration as well as errors delegated to PHP. Keep access to the error log restricted. PHP error configuration
display_errors = Off
display_startup_errors = Off
log_errors = On
error_reporting = E_ALLregister() installs the error and exception callbacks once per run and returns the run. The older load() entry point also registers the run. When using Blunder in a worker or a scoped task, call unregister() in finally to restore the previous callbacks and their error mask. Unregister nested runs in reverse order, and restore any later PHP callbacks before unregistering the run they cover.
<?php
use MaplePHP\Blunder\ExceptionItem;
use MaplePHP\Blunder\Handlers\SilentHandler;
use MaplePHP\Blunder\Run;
require __DIR__ . '/vendor/autoload.php';
$run = new Run(new SilentHandler());
$run->event(static function (ExceptionItem $item): void {
echo $item->getMessage(), PHP_EOL;
});
$run->register();
try {
trigger_error('Scoped diagnostic', E_USER_WARNING);
} finally {
$run->unregister();
}Use setExitCode(1) to request a failing process status when an error is emitted. Use disableExitCode() or setExitCode(null) to leave exit to the caller or PHP. These options apply to the owning run.
Call removeLocationHeader(true) before registration to clear a pending Location header while PHP can still change headers. A prepared error response also drops the original redirect and replaces the body.
Configure the severity pool before registration. strict() accepts a bitmask, such as E_WARNING | E_USER_WARNING. Its default is E_ALL. A zero mask disables Blunder’s PHP diagnostic callback for those levels while the exception callback remains registered. setSeverityLevels() accepts a list of individual error constants. Blunder respects the active error_reporting() mask and PHP’s suppression rules. PHP error constants
silence($glob, $levels) suppresses a diagnostic in Blunder when its file and severity match. The glob is case-sensitive and matches the full path, with either slash style accepted. Asterisks can span directories. Use excludeSeverityLevels() to hand selected diagnostics back to PHP or make them available to a redirect callback.
<?php
use MaplePHP\Blunder\Handlers\JsonHandler;
use MaplePHP\Blunder\Handlers\SilentHandler;
use MaplePHP\Blunder\Run;
require __DIR__ . '/vendor/autoload.php';
$run = new Run(new SilentHandler());
$run->severity()
->strict(E_ALL)
->silence(__FILE__, E_USER_NOTICE)
->excludeSeverityLevels([E_WARNING, E_USER_WARNING, E_DEPRECATED, E_USER_DEPRECATED])
->redirectTo(static function (int $level, string $message, string $file, int $line): bool|JsonHandler {
if ($level === E_DEPRECATED || $level === E_USER_DEPRECATED) {
error_log("Deprecated: $message in $file on line $line");
return true;
}
return new JsonHandler();
});
$run->register();
try {
trigger_error('Hidden by the path rule', E_USER_NOTICE);
trigger_error('Log this deprecation', E_USER_DEPRECATED);
trigger_error('Render this warning as JSON', E_USER_WARNING);
} finally {
$run->unregister();
}The callback receives the severity, message, file, line and context array. Its return value controls the excluded diagnostic.
| Callback result | Effect |
|---|---|
true |
Suppress the diagnostic after any work done in the callback. |
false |
Delegate to PHP’s native handler. |
null or no return |
Continue through normal Blunder handling. |
A HandlerInterface instance |
Supply an alternate formatter for the diagnostic. |
redirectTo(null) clears the callback and sends excluded levels back to PHP. Silence rules run before the redirect and the deprecation collector.
Opt in to collectDeprecations() to count eligible E_DEPRECATED and E_USER_DEPRECATED diagnostics without rendering them. The summary keeps up to 100 distinct diagnostics grouped by severity, message, file and line. total includes every collected occurrence and overflow counts occurrences outside the retained entries. Suppressed diagnostics and ones consumed by a redirect stay out of the summary.
<?php
use MaplePHP\Blunder\Handlers\SilentHandler;
use MaplePHP\Blunder\Run;
require __DIR__ . '/vendor/autoload.php';
$run = new Run(new SilentHandler());
$pool = $run->severity()->collectDeprecations();
$run->register();
try {
for ($index = 0; $index < 2; $index++) {
trigger_error('An older method will be removed', E_USER_DEPRECATED);
}
} finally {
$run->unregister();
}
$summary = $pool->getDeprecations();
echo $summary['total'], ' deprecations in ', count($summary['entries']), ' entry', PHP_EOL;render($error) returns a string from the base formatter without running the handler stack or notifying listeners. capture($error) follows the handler stack and notifies listeners without sending the prepared response or applying the process exit code. Neither operation requires global registration.
Push handlers or callback decisions with pushHandler(). The most recently pushed entry runs first. A handler instance formats the error. A callback receives the ExceptionItem and optional original HTTP context. Return HandlerDecision::Continue or null to try the next entry, or HandlerDecision::Stop to handle the error without a response body. The configured base handler is the final choice unless a severity redirect supplies an alternate.
<?php
use MaplePHP\Blunder\Enums\HandlerDecision;
use MaplePHP\Blunder\ExceptionItem;
use MaplePHP\Blunder\Handlers\JsonHandler;
use MaplePHP\Blunder\Handlers\PlainTextHandler;
use MaplePHP\Blunder\Run;
require __DIR__ . '/vendor/autoload.php';
$steps = [];
$run = (new Run(new PlainTextHandler()))->setExitCode(7);
$run->pushHandler(new JsonHandler());
$run->pushHandler(static function (ExceptionItem $item) use (&$steps): HandlerDecision {
$steps[] = 'stack callback';
return HandlerDecision::Continue;
});
foreach (['first listener', 'second listener'] as $name) {
$run->event(static function () use (&$steps, $name): void {
$steps[] = $name;
});
}
$error = new RuntimeException('Example error');
$plain = $run->render($error);
$report = $run->capture($error);
echo $plain, PHP_EOL, $report->body, PHP_EOL;
echo implode(' → ', $steps), PHP_EOL;
echo 'Intended exit status ', $report->exitCode, PHP_EOL;Listeners run in registration order after the selected handler prepares its response and before emission. A listener can accept the ExceptionItem, original HttpMessagingInterface context and prepared PSR-7 response. Either HTTP argument may be null. For example, a stopped or silent dispatch has no prepared response.
A CapturedError contains item, body, response, status and exitCode. The latter three can be null. The original error stays available through $report->item and $run->getLastHandledItem(). A CaptureHandler can also retain the most recent report from a registered dispatch through getLastCapturedError().
If a formatter or listener fails, Blunder can return a minimal fallback report for the original exception. Production fallback leaves out details. A captured fallback can have a plain-text 500 response even when the selected handler normally emits another format. Built-in handlers support controlled formatting and capture. A legacy handler that writes its own output is for live dispatch.
<?php
use MaplePHP\Blunder\Handlers\JsonHandler;
use MaplePHP\Blunder\Run;
require __DIR__ . '/vendor/autoload.php';
$run = (new Run(new JsonHandler()))->production();
$run->event(static function (): void {
throw new RuntimeException('The listener failed');
});
$report = $run->capture(new RuntimeException('Original exception'));
echo $report->status, PHP_EOL, $report->body, PHP_EOL;Handlers live in MaplePHP\Blunder\Handlers.
| Handler | Output and HTTP media type |
|---|---|
HtmlHandler |
Detailed error page with trace navigation, excerpts and request context. text/html; charset=utf-8 |
TextHandler |
Escaped preformatted diagnostic in HTML. text/html; charset=utf-8 |
PlainTextHandler |
Plain-text diagnostic. text/plain; charset=utf-8 |
CliHandler |
Console diagnostic with optional terminal color. text/plain; charset=utf-8 |
JsonHandler |
JSON error object. application/json; charset=utf-8 |
JsonHandler with useJsonApi() |
JSON:API error document. application/vnd.api+json |
XmlHandler |
XML document rooted at <xml>. application/xml; charset=utf-8 |
SilentHandler |
Listener-only handling by default. Pass true to opt into development output for errors classified as fatal or at the log level error. |
CaptureHandler |
Retains a plain-text report for programmatic use without emitting it. |
In development, the default JSON object contains status, message, flag, file, line, code and trace. The status field here is a log level. XML uses the same diagnostic names and represents the trace as <frame> elements. When a cause exists, both include a previous section. JSON:API uses an errors array with a string HTTP status, code, title, detail and diagnostic meta.
Call enableTraceLines(false) for a shorter diagnostic. Ordinary JSON keeps an empty trace array, XML keeps an empty trace element and JSON:API omits meta.trace. Messages retain their text through JSON encoding or XML escaping. Production uses generic format-specific bodies. Its JSON:API error objects contain only status and title.
Pass an existing PSR-7 request and response through HttpMessaging. For a normal error response, a valid 4xx or 5xx from the top-level exception's getHttpStatusCode() takes precedence. Blunder then uses a 4xx or 5xx already set on the supplied response, or defaults to 500. The prepared response uses a fresh body, preserves applicable headers and sends separate Set-Cookie fields. It clears stale representation metadata and sends Cache-Control: no-store.
<?php
use MaplePHP\Blunder\Handlers\JsonHandler;
use MaplePHP\Blunder\HttpMessaging;
use MaplePHP\Blunder\Interfaces\HttpStatusExceptionInterface;
use MaplePHP\Blunder\Run;
use MaplePHP\Http\ResponseFactory;
require __DIR__ . '/vendor/autoload.php';
$error = new class ('Try again later') extends RuntimeException implements HttpStatusExceptionInterface {
public function getHttpStatusCode(): int
{
return 429;
}
};
$request = (new HttpMessaging())->request();
$response = (new ResponseFactory())->createResponse(503)->withHeader('Retry-After', '60');
$http = new HttpMessaging($response, $request);
$handler = (new JsonHandler())->useJsonApi()->enableTraceLines(false);
$report = (new Run($handler, $http))->capture($error);
echo $report->status, PHP_EOL, $report->body, PHP_EOL;CLI settings are per handler. useStderr() sends reports to STDERR. Color uses the selected stream’s TTY capability and the terminal style support available in MaplePHP Prompts. Redirected streams, TERM=dumb and a nonempty NO_COLOR receive plain output. Call enableColor(false) to force plain output. enableColor(true) restores automatic detection.
<?php
use MaplePHP\Blunder\Handlers\CliHandler;
use MaplePHP\Blunder\Run;
require __DIR__ . '/vendor/autoload.php';
$handler = (new CliHandler())
->useStderr()
->enableColor(false)
->enableTraceLines(true)
->enableCodeExcerpt()
->setProjectRoot(__DIR__);
$run = (new Run($handler))->setExitCode(1);
$run->register();
throw new RuntimeException('CLI example');HTML diagnostics include previous causes even when their source is unavailable. Configuring a project root shortens paths inside it and restricts source previews to local regular files within it. The page groups vendor frames under a collapsed section and follows the browser's color preference.
The development page hides known credentials and copies of them across request context and diagnostics. It removes user information from displayed URLs and can omit diagnostic details when redaction limits are reached. Add case-insensitive key or glob rules with setRedactionPatterns(). setContext() adds a field map and addDataTable() adds a named table. A table callback receives the ExceptionItem and original HTTP context once per debug render. Table titles, keys and values pass through the same redaction and escaping as request context. A failing callback leaves out its table.
An exception can implement SolutionInterface::getSolution(): ?string to supply a plain-text hint. Without a hint, configured SolutionProviderInterface implementations are tried in registration order. The built-in matcher then checks for common PHP messages about undefined variables, missing methods or missing classes.
<?php
use MaplePHP\Blunder\ExceptionItem;
use MaplePHP\Blunder\Handlers\HtmlHandler;
use MaplePHP\Blunder\Interfaces\HttpMessagingInterface;
use MaplePHP\Blunder\Interfaces\SolutionInterface;
use MaplePHP\Blunder\Interfaces\SolutionProviderInterface;
use MaplePHP\Blunder\Run;
require __DIR__ . '/vendor/autoload.php';
$handler = new HtmlHandler();
$handler->setProjectRoot(__DIR__);
$handler->setRedactionPatterns(['internal*']);
$handler->setContext(['feature' => 'report export']);
$handler->addDataTable('Request summary', static function (ExceptionItem $item, HttpMessagingInterface $http): array {
return [
'method' => $http->request()->getMethod(),
'exception' => $item->getType(),
'internalReference' => 'request-215',
];
});
$handler->addSolutionProvider(new class implements SolutionProviderInterface {
public function getSolution(ExceptionItem $exception): ?string
{
return 'Check the export settings.';
}
});
$handler->setEditor('vscode');
$handler->setPathMappings([__DIR__ => '/workspace/report-app']);
(new Run($handler))->register();
throw new class ('The report could not be exported') extends RuntimeException implements SolutionInterface {
public function getSolution(): ?string
{
return 'Create the export directory and retry.';
}
};The editor presets are vscode, vscode-insiders, phpstorm and textmate. Use a URL scheme registered by your editor. For a custom editor, give setEditor() an absolute editor URI template with {file} and {line}, such as my-editor://open?file={file}&line={line}. A callback receives the mapped absolute path and line and returns a complete editor URI or null. Encode URL components when building the callback result. setEditor(null) disables links.
Links require a local file inside the project root and a positive source line. The working directory is the default boundary for editor links. Optional mappings translate absolute project-side prefixes into editor-side paths. Blunder picks the longest matching directory prefix. In the example, replace /workspace/report-app with the directory visible to your editor.
The page attaches a nonce to its script and style. If your application already sends a Content Security Policy, pass the matching nonce to setCspNonce().
ExceptionItem::getTrace(0) returns the current exception’s original trace positions with argument types and full paths. getFrames() exposes immutable frame metadata across the chain, including source-less calls, up to 128 frames across 32 exceptions. Use filter() or map() to create a new collection, and withComment() to annotate a frame while retaining its ID. getPreviousExceptions() returns up to 31 causes, closest first.
Source reads are lazy. Frame::getSource() reads ten lines before the target and twelve after it by default. The scan is bounded to 8 MiB, each returned line to 4 KiB, and each side of the window to 100 lines. A missing or ineligible file returns an empty excerpt.
Install MaplePHP’s PSR-3 logger to run this example. The example writes a temporary file at $path. In an application, use a protected log directory outside the web root. MaplePHP Log
composer require maplephp/log<?php
use MaplePHP\Blunder\ExceptionItem;
use MaplePHP\Blunder\Handlers\SilentHandler;
use MaplePHP\Blunder\Run;
use MaplePHP\Log\Handlers\StreamHandler;
use MaplePHP\Log\Logger;
require __DIR__ . '/vendor/autoload.php';
$path = tempnam(sys_get_temp_dir(), 'blunder-log-');
if ($path === false) {
throw new RuntimeException('Could not create a log file');
}
$logger = new Logger(new StreamHandler($path));
$run = (new Run(new SilentHandler()))->production();
$run->event(static function (ExceptionItem $item) use ($logger): void {
$logger->log($item->getStatus(), 'Application diagnostic', [
'severity' => $item->getSeverity(),
'file' => $item->getFile(),
'line' => $item->getLine(),
'message' => $item->getMessage(),
]);
});
$run->register();
try {
trigger_error('Example maintenance notice', E_USER_NOTICE);
} finally {
$run->unregister();
}Pass the original as the new exception’s previous cause. When wrapping a BlunderErrorException, call preserveExceptionOrigin() to carry its file and line to the replacement exception.
<?php
use MaplePHP\Blunder\Exceptions\BlunderErrorException;
use MaplePHP\Blunder\Handlers\PlainTextHandler;
use MaplePHP\Blunder\Run;
require __DIR__ . '/vendor/autoload.php';
try {
throw new BlunderErrorException('Original failure', 0, E_WARNING, __FILE__, __LINE__);
} catch (BlunderErrorException $cause) {
$wrapped = new RuntimeException('Could not export the report', 0, $cause);
$cause->preserveExceptionOrigin($wrapped);
echo (new Run(new PlainTextHandler()))->render($wrapped);
}