Search by

webservco / exception

ariademur

A PHP component/library. Exception handlers that log the exception, for both caught exceptions and the ones nothing else catches.

Package info

github.com/webservco/exception

Homepage

pkg:composer/webservco/exception

Statistics

Installs: 518

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

v2.3.0 2026-10-11 16:34 UTC

This package is auto-updated.

Last update: 2026-10-11 16:45:39 UTC


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 (ExceptionHandlerMiddleware uses 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

License

MIT