webservco / exception
PHP组件/库。
v0.8.0
2024-06-22 15:10 UTC
Requires
- php: ^8.3
- psr/log: ^3
Requires (Dev)
- pds/skeleton: ^1
- phan/phan: ^5
- php-parallel-lint/php-console-highlighter: ^1
- php-parallel-lint/php-parallel-lint: ^1
- phpcompatibility/php-compatibility: ^9
- phpmd/phpmd: ^2
- phpstan/phpstan: ^1
- phpstan/phpstan-phpunit: ^1
- phpstan/phpstan-strict-rules: ^1
- phpunit/phpunit: ^10
- slevomat/coding-standard: ^8
- squizlabs/php_codesniffer: ^3
- vimeo/psalm: ^5
- webservco/coding-standards: ^0
- webservco/component-common: ^0
README
PHP组件/库。
自定义应用程序异常处理。
使用方法
实现接口
ExceptionHandlerFactoryInterface
interface ExceptionHandlerFactoryInterface { public function createExceptionHandler(LoggerInterface $logger): ExceptionHandlerInterface; }
ExceptionHandlerInterface
interface ExceptionHandlerInterface { public function handle(Throwable $throwable): void; }
UncaughtExceptionHandlerInterface
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)); } } }