SafeCaller.php 965 B

123456789101112131415161718192021222324252627282930313233343536373839
  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\Support;
  12. use Closure;
  13. use Hyperf\Contract\StdoutLoggerInterface;
  14. use Psr\Container\ContainerInterface;
  15. use Psr\Log\LogLevel;
  16. use Throwable;
  17. class SafeCaller
  18. {
  19. public function __construct(private ContainerInterface $container)
  20. {
  21. }
  22. public function call(Closure $closure, ?Closure $default = null, string $level = LogLevel::CRITICAL): mixed
  23. {
  24. try {
  25. return $closure();
  26. } catch (Throwable $exception) {
  27. if ($this->container->has(StdoutLoggerInterface::class) && $logger = $this->container->get(StdoutLoggerInterface::class)) {
  28. $logger->log($level, (string) $exception);
  29. }
  30. }
  31. return value($default);
  32. }
  33. }