webservco / exception
A PHP component/library. Exception handlers that log the exception, for both caught exceptions and the ones nothing else catches.
Requires
- php: ^8.4
- psr/log: ^3
Requires (Dev)
- pds/skeleton: ^1
- phan/phan: ^6
- php-parallel-lint/php-console-highlighter: ^1
- php-parallel-lint/php-parallel-lint: ^1
- phpmd/phpmd: ^3
- phpstan/phpstan: ^2
- phpstan/phpstan-deprecation-rules: ^2
- phpstan/phpstan-phpunit: ^2
- phpstan/phpstan-strict-rules: ^2
- phpunit/phpunit: ^13
- slevomat/coding-standard: ^8
- squizlabs/php_codesniffer: ^4
- vimeo/psalm: ^6
- webservco/coding-standards: ^2
- webservco/component-common: ^2
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A PHP component/library. Please see webservco/sandbox for an example project using these types of components.
Exception handlers that log the exception, for both caught exceptions and the ones nothing else catches.
- Related:
webservco/middleware(ExceptionHandlerMiddlewareuses a handler from here),webservco/error(turns PHP errors into exceptions)
Installation
composer require webservco/exception
Usage
Uncaught exceptions
Set this handler early in the entry point, as soon as the logger exists.
use WebServCo\Exception\Factory\DefaultExceptionHandlerFactory; $exceptionHandlerFactory = new DefaultExceptionHandlerFactory(); // $logger: \Psr\Log\LoggerInterface set_exception_handler([$exceptionHandlerFactory->createUncaughtExceptionHandler($logger), 'handle']);
Caught exceptions
Inside the application, log an exception and keep going. The webservco/sandbox project passes this handler to ExceptionHandlerMiddleware, which logs the exception and then renders an error page.
// \WebServCo\Exception\Contract\ExceptionHandlerInterface $exceptionHandler = $exceptionHandlerFactory->createExceptionHandler($logger); try { $service->doSomething(); } catch (Throwable $throwable) { $exceptionHandler->handle($throwable); }
Contracts
| Interface | Implementation | Purpose |
|---|---|---|
Contract\ExceptionHandlerInterface |
Service\DefaultExceptionHandler |
Logs the exception. |
Contract\UncaughtExceptionHandlerInterface |
Service\DefaultUncaughtExceptionHandler |
Logs the exception, sets status 500 and prints a short message. |
Contract\ExceptionHandlerFactoryInterface |
Factory\DefaultExceptionHandlerFactory |
Creates both handlers for a logger. |
Namespaces are relative to WebServCo\Exception\.
Notes
Both handlers log the message at error level, with the exception in the context under throwable, and also send it to PHP's system log with error_log().
The uncaught handler prints only Application exception. and keeps the details in the log. It doesn't set the status code under the cli and cgi-fcgi SAPIs.
To also report errors to an external service, extend Service\AbstractExceptionHandler and call its log() method from your handle().
Development
# Start project. ddev start # Install dependencies. ddev c u # Run all validations. ddev c c # Run unit tests. ddev c test:dox