src/App/Subscriber/ConsoleExceptionSubscriber.php line 39

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace App\Subscriber;
  3. use App\Email\ConsoleExceptionType;
  4. use PhpAmqpLib\Exception\AMQPTimeoutException;
  5. use Sindrive\EmailSenderBundle\Service\EmailSender;
  6. use Symfony\Component\Console\ConsoleEvents;
  7. use Symfony\Component\Console\Event\ConsoleCommandEvent;
  8. use Symfony\Component\Console\Event\ConsoleErrorEvent;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. class ConsoleExceptionSubscriber implements EventSubscriberInterface
  11. {
  12.     private EmailSender $emailSender;
  13.     public function __construct(EmailSender $emailSender)
  14.     {
  15.         $this->emailSender $emailSender;
  16.     }
  17.     /**
  18.      * @return array<string, array<int|string, array<int|string, int|string>|int|string>|string>
  19.      */
  20.     public static function getSubscribedEvents(): array
  21.     {
  22.         return [
  23.             ConsoleEvents::ERROR => 'onError',
  24.             ConsoleEvents::COMMAND => 'onCommand',
  25.         ];
  26.     }
  27.     public function onCommand(ConsoleCommandEvent $event): void
  28.     {
  29.         // nothing - initialize EmailSender on each command before any output
  30.     }
  31.     public function onError(ConsoleErrorEvent $event): void
  32.     {
  33.         $exception $event->getError();
  34.         $input $event->getInput();
  35.         if ($exception instanceof AMQPTimeoutException) {
  36.             return;
  37.         }
  38.         $subject 'Command error';
  39.         if (null !== $event->getCommand()) {
  40.             $subject $event->getCommand()->getName() . ' ' $subject;
  41.         }
  42.         $body 'Input: arguments: ' json_encode($input->getArguments(), JSON_THROW_ON_ERROR);
  43.         $body .= ' options: ' json_encode($input->getOptions(), JSON_THROW_ON_ERROR);
  44.         $body .= '<br/>';
  45.         $body .= '<br/>';
  46.         $body .= $exception->getMessage();
  47.         $body .= '<br/>';
  48.         $body .= $exception->getFile() . '  Line: ' $exception->getLine();
  49.         $body .= '<br/>';
  50.         $body .= '<br/>';
  51.         $body .= $exception->getTraceAsString();
  52.         $this->emailSender->sendType(new ConsoleExceptionType($subject$body));
  53.     }
  54. }