ExceptionHandlerDispatcher.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\ExceptionHandler;
  12. use Hyperf\Context\ResponseContext;
  13. use Hyperf\Dispatcher\AbstractDispatcher;
  14. use InvalidArgumentException;
  15. use Psr\Container\ContainerInterface;
  16. use Throwable;
  17. class ExceptionHandlerDispatcher extends AbstractDispatcher
  18. {
  19. public function __construct(private ContainerInterface $container)
  20. {
  21. }
  22. public function dispatch(...$params)
  23. {
  24. /**
  25. * @param Throwable $throwable
  26. * @param string[] $handlers
  27. */
  28. [$throwable, $handlers] = $params;
  29. $response = ResponseContext::get();
  30. foreach ($handlers as $handler) {
  31. if (! $this->container->has($handler)) {
  32. throw new InvalidArgumentException(sprintf('Invalid exception handler %s.', $handler));
  33. }
  34. $handlerInstance = $this->container->get($handler);
  35. if (! $handlerInstance instanceof ExceptionHandler || ! $handlerInstance->isValid($throwable)) {
  36. continue;
  37. }
  38. $response = $handlerInstance->handle($throwable, $response);
  39. if ($handlerInstance->isPropagationStopped()) {
  40. break;
  41. }
  42. }
  43. return $response;
  44. }
  45. }