PHP code example of webservco / exception

1. Go to this page and download the library: Download webservco/exception library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

webservco / exception example snippets


interface ExceptionHandlerFactoryInterface
{
    public function createExceptionHandler(LoggerInterface $logger): ExceptionHandlerInterface;
}

interface ExceptionHandlerInterface
{
    public function handle(Throwable $throwable): void;
}

interface UncaughtExceptionHandlerInterface extends ExceptionHandlerInterface
{
}

// Exception handling.
$exceptionHandlerFactory = new DefaultExceptionHandlerFactory();
// Uncaught exception handler.
set_exception_handler([$exceptionHandlerFactory->createUncaughtExceptionHandler($logger), 'handle']);

$exceptionHandler = $exceptionHandlerFactory->createExceptionHandler($logger);

// Example: an exception handling middleware.
final class ExceptionHandlerMiddleware implements MiddlewareInterface
{
    public function __construct(
        // Exception handler to use to handle the exception.
        private ExceptionHandlerInterface $exceptionHandler,
        // Request handler to use to return a response to the client
        private RequestHandlerInterface $requestHandler,
    ) {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            /**
             * Pass to the next handler.
             * If all is OK, nothing else to do.
             */
            return $handler->handle($request);
        } catch (Throwable $throwable) {
            /**
             * An exception happened inside one of the next handlers.
             */

            // Handle error (log, report, etc)
            $this->exceptionHandler->handle($throwable);

            /**
             * Return a response via the request handler.
             * Any exceptions that happen here will bubble up and be handled by the uncaught exception handler (if set).
             */
            return $this->requestHandler->handle($request->withAttribute('throwable', $throwable));
        }
    }
}