Universal package for handling exceptions and HTTP errors.
composer require codemonster-ru/errorsIt can be used as part of a framework or on its own in any PHP project.
use Codemonster\Errors\Contracts\ExceptionHandlerInterface;
use Codemonster\Errors\Handlers\SmartExceptionHandler;
use Codemonster\Http\Response;
require __DIR__ . '/vendor/autoload.php';
$handler = new SmartExceptionHandler();
set_exception_handler(function (Throwable $e) use ($handler) {
$response = $handler->handle($e);
if (php_sapi_name() !== 'cli') {
http_response_code($response->getStatusCode());
echo (string) $response;
} else {
fwrite(STDERR, (string) $response . PHP_EOL);
}
});
throw new RuntimeException('Something went wrong!');When you run it, you'll get a neat HTML page (or a text fallback in the CLI), with error information and the correct HTTP code.
use Codemonster\Errors\Handlers\SmartExceptionHandler;
use Codemonster\View\View;
$view = new View(...);
$viewRenderer = fn(string $template, array $data) => $view->render($template, $data);
$handler = new SmartExceptionHandler($viewRenderer, debug: true);
try {
throw new RuntimeException('Demo error');
} catch (Throwable $e) {
$response = $handler->handle($e);
echo $response;
}resources/views/errors/
├── generic.php # error page for production
└── debug.php # debug page for developers
You can run tests with the command:
composer test