getThrowable example

namespace Symfony\Component\Messenger\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
use Symfony\Component\Messenger\Stamp\ErrorDetailsStamp;

final class AddErrorDetailsStampListener implements EventSubscriberInterface
{
    public function onMessageFailed(WorkerMessageFailedEvent $event): void
    {
        $stamp = ErrorDetailsStamp::create($event->getThrowable());
        $previousStamp = $event->getEnvelope()->last(ErrorDetailsStamp::class);

        // Do not append duplicate information         if (null === $previousStamp || !$previousStamp->equals($stamp)) {
            $event->addStamps($stamp);
        }
    }

    public static function getSubscribedEvents(): array
    {
        return [
            
throw new NotFoundHttpException($message$e);
        } catch (MethodNotAllowedException $e) {
            $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod()$request->getUriForPath($request->getPathInfo())implode(', ', $e->getAllowedMethods()));

            throw new MethodNotAllowedHttpException($e->getAllowedMethods()$message$e);
        }
    }

    public function onKernelException(ExceptionEvent $event): void
    {
        if (!$this->debug || !($e = $event->getThrowable()) instanceof NotFoundHttpException) {
            return;
        }

        if ($e->getPrevious() instanceof NoConfigurationException) {
            $event->setResponse($this->createWelcomeResponse());
        }
    }

    public static function getSubscribedEvents(): array
    {
        return [
            
'exception' => (string) $exception,
            'message' => 'Test',
            'template' => '{{ subject }}',
            'eventName' => 'checkout.order.placed',
            'templateData' => [
                'eventName' => 'checkout.order.placed',
                'shopName' => 'Storefront',
            ],
        ]$event->getLogData());
        static::assertSame('mail.sent.error', $event->getName());
        static::assertSame($context$event->getContext());
        static::assertSame($exception$event->getThrowable());
    }
}
$event->stopPropagation();

        $salesChannelId = $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID, '');
        $domainId = $request->attributes->get(SalesChannelRequest::ATTRIBUTE_DOMAIN_ID, '');
        $languageId = $request->attributes->get(PlatformRequest::HEADER_LANGUAGE_ID, '');

        if (!$request->attributes->has(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT)) {
            // When no sales-channel context is resolved, we need to resolve it now.             $this->setSalesChannelContext($request);
        }

        $is404StatusCode = $event->getThrowable() instanceof HttpException && $event->getThrowable()->getStatusCode() === Response::HTTP_NOT_FOUND;

        // If the exception is not a 404 status code, we don't need to cache it.         if (!$is404StatusCode) {
            $event->setResponse($this->controller->error(
                $event->getThrowable(),
                $request,
                $event->getRequest()->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT)
            ));

            return;
        }

        

    public function unregister(EventDispatcherInterface $dispatcher): void
    {
        $dispatcher->removeListener(KernelEvents::EXCEPTION, $this->onKernelException(...));
    }

    /** * Handles security related exceptions. */
    public function onKernelException(ExceptionEvent $event): void
    {
        $exception = $event->getThrowable();
        do {
            if ($exception instanceof AuthenticationException) {
                $this->handleAuthenticationException($event$exception);

                return;
            }

            if ($exception instanceof AccessDeniedException) {
                $this->handleAccessDeniedException($event$exception);

                return;
            }
    return -75;
  }

  /** * Handles all 4xx errors for JSON. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event * The event to process. */
  public function on4xx(ExceptionEvent $event) {
    /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
    $exception = $event->getThrowable();

    // If the exception is cacheable, generate a cacheable response.     if ($exception instanceof CacheableDependencyInterface) {
      $response = new CacheableJsonResponse(['message' => $event->getThrowable()->getMessage()]$exception->getStatusCode()$exception->getHeaders());
      $response->addCacheableDependency($exception);
    }
    else {
      $response = new JsonResponse(['message' => $event->getThrowable()->getMessage()]$exception->getStatusCode()$exception->getHeaders());
    }

    $event->setResponse($response);
  }
/** * @dataProvider getAuthenticationExceptionProvider */
    public function testAuthenticationExceptionWithoutEntryPoint(\Exception $exception, \Exception $eventException)
    {
        $event = $this->createEvent($exception);

        $listener = $this->createExceptionListener();
        $listener->onKernelException($event);

        $this->assertNull($event->getResponse());
        $this->assertEquals($eventException$event->getThrowable());
    }

    /** * @dataProvider getAuthenticationExceptionProvider */
    public function testAuthenticationExceptionWithEntryPoint(\Exception $exception)
    {
        $event = $this->createEvent($exception);

        $response = new Response('Forbidden', 403);

        
public function __construct(Connection $connection) {
    $this->connection = $connection;
  }

  /** * Handles errors for this subscriber. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event * The event to process. */
  public function onException(ExceptionEvent $event) {
    $exception = $event->getThrowable();
    if ($this->shouldRedirectToInstaller($exception$this->connection)) {
      // Only redirect if this is an HTML response (i.e., a user trying to view       // the site in a web browser before installing it).       $request = $event->getRequest();
      $format = $request->query->get(MainContentViewSubscriber::WRAPPER_FORMAT, $request->getRequestFormat());
      if ($format == 'html') {
        $event->setResponse(new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']));
      }
    }
  }

  


    /** * Catch exceptions: true * Throwable type: RuntimeException * Listener: true. */
    public function testHandleWhenControllerThrowsAnExceptionAndCatchIsTrueWithAHandlingListener()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::EXCEPTION, function D$event) {
            $event->setResponse(new Response($event->getThrowable()->getMessage()));
        });

        $kernel = $this->getHttpKernel($dispatcherstatic fn () => throw new \RuntimeException('foo'));
        $response = $kernel->handle(new Request(), HttpKernelInterface::MAIN_REQUEST, true);

        $this->assertEquals('500', $response->getStatusCode());
        $this->assertEquals('foo', $response->getContent());
    }

    /** * Catch exceptions: true * Throwable type: TypeError * Listener: true. */


    /** * Handles a throwable by trying to convert it to a Response. */
    private function handleThrowable(\Throwable $e, Request $request, int $type): Response
    {
        $event = new ExceptionEvent($this$request$type$e);
        $this->dispatcher->dispatch($event, KernelEvents::EXCEPTION);

        // a listener might have replaced the exception         $e = $event->getThrowable();

        if (!$event->hasResponse()) {
            $this->finishRequest($request$type);

            throw $e;
        }

        $response = $event->getResponse();

        // the developer asked for a specific status code         if (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
            
use Symfony\Component\HttpKernel\KernelEvents;

/** * Handle the EnforcedResponseException and deliver an EnforcedResponse. */
class EnforcedFormResponseSubscriber implements EventSubscriberInterface {

  /** * Replaces the response in case an EnforcedResponseException was thrown. */
  public function onKernelException(ExceptionEvent $event) {
    if ($response = EnforcedResponse::createFromException($event->getThrowable())) {
      // Setting the response stops the event propagation.       $event->setResponse($response);
    }
  }

  /** * Unwraps an enforced response. */
  public function onKernelResponse(ResponseEvent $event) {
    $response = $event->getResponse();
    if ($response instanceof EnforcedResponse && $event->isMainRequest()) {
      

  public function onExceptionSendChallenge(ExceptionEvent $event) {
    if (isset($this->challengeProvider) && $event->isMainRequest()) {
      $request = $event->getRequest();
      $exception = $event->getThrowable();
      if ($exception instanceof AccessDeniedHttpException && !$this->authenticationProvider->applies($request) && (!isset($this->filter) || $this->filter->appliesToRoutedRequest($request, FALSE))) {
        $challenge_exception = $this->challengeProvider->challengeException($request$exception);
        if ($challenge_exception) {
          $event->setThrowable($challenge_exception);
        }
      }
    }
  }

  /** * Detect disallowed authentication methods on access denied exceptions. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event * The event. */


    /** * Handles a throwable by trying to convert it to a Response. */
    private function handleThrowable(\Throwable $e, Request $request, int $type): Response
    {
        $event = new ExceptionEvent($this$request$type$e);
        $this->dispatcher->dispatch($event, KernelEvents::EXCEPTION);

        // a listener might have replaced the exception         $e = $event->getThrowable();

        if (!$event->hasResponse()) {
            $this->finishRequest($request$type);

            throw $e;
        }

        $response = $event->getResponse();

        // the developer asked for a specific status code         if (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
            
$request->query->set(MainContentViewSubscriber::WRAPPER_FORMAT, 'html');
    }
  }

  /** * Catches a form AJAX exception and build a response from it. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event * The event to process. */
  public function onException(ExceptionEvent $event) {
    $exception = $event->getThrowable();
    $request = $event->getRequest();

    // Render a nice error message in case we have a file upload which exceeds     // the configured upload limit.     if ($exception instanceof BrokenPostRequestException && $request->query->has(FormBuilderInterface::AJAX_FORM_REQUEST)) {
      $this->messenger->addError($this->t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', ['@size' => $this->formatSize($exception->getSize())]));
      $response = new AjaxResponse(NULL, 200);
      $status_messages = ['#type' => 'status_messages'];
      $response->addCommand(new PrependCommand(NULL, $status_messages));
      $event->allowCustomResponseCode();
      $event->setResponse($response);
      
$session->set(PlatformRequest::HEADER_CONTEXT_TOKEN, $token);
        $master->headers->set(PlatformRequest::HEADER_CONTEXT_TOKEN, $token);
    }

    public function customerNotLoggedInHandler(ExceptionEvent $event): void
    {
        if (!$event->getRequest()->attributes->has(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
            return;
        }

        if (!$event->getThrowable() instanceof CustomerNotLoggedInException) {
            return;
        }

        $request = $event->getRequest();

        $parameters = [
            'redirectTo' => $request->attributes->get('_route'),
            'redirectParameters' => json_encode($request->attributes->get('_route_params'), \JSON_THROW_ON_ERROR),
        ];

        $redirectResponse = new RedirectResponse($this->router->generate('frontend.account.login.page', $parameters));

        
Home | Imprint | This part of the site doesn't use cookies.