Skip to content

ErrorHandlingMiddleware

Catches unhandled throwables from downstream middleware/action dispatch and produces a generic 500 (or mapped) response.

Currently minimal; can be extended to perform content negotiation (HTML/JSON) and structured logging.

class ErrorHandlingMiddleware implements MiddlewareInterface

ImplementsMiddlewareInterface
SourceMiddleware/ErrorHandlingMiddleware.php

public function __construct(callable(Throwable $e, ServerRequestInterface $r): void|null $logger = null): mixed

ParameterTypeDescription
$logger`callable(Throwable $e, ServerRequestInterface $r): void““null`

Returns mixed

MethodDescription
process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterfaceCatches any throwable escaping the rest of the stack and renders it as a response.
renderExceptionResponse(ServerRequestInterface $request, Throwable $e): ResponseInterfacePublic helper so Kernel (or other bootstrap code) can render a unified exception response.

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface

Catches any throwable escaping the rest of the stack and renders it as a response.

Logs a single diagnostic line carrying the exception class, message, throw site, the triggering request, the cause chain and the trace, then hands the exception to ErrorHandlingMiddleware::renderExceptionResponse() for the actual body and status. Nothing propagates out of here, which is the point of its high bootstrap priority: everything ordered inside it is covered.

Middleware that must see error and 404 responses has to be ordered outside this one; after: ErrorHandlingMiddleware places it within the try and it will be skipped whenever an exception is thrown.

ParameterTypeDescription
$requestServerRequestInterface
$handlerRequestHandlerInterface

Returns ResponseInterface

public function renderExceptionResponse(ServerRequestInterface $request, Throwable $e): ResponseInterface

Public helper so Kernel (or other bootstrap code) can render a unified exception response.

ParameterTypeDescription
$requestServerRequestInterface
$eThrowable

Returns ResponseInterface