How to issue 404 from a KernelEvents::REQUEST event I'm trying to issue a 404 from a KernelEvents::REQUEST event, but it's resulting in the following error:

Fatal error: Maximum function nesting level of '256' reached, aborting! in /var/www/vendor/symfony/http-foundation/HeaderBag.php on line 162


Here's my class

&lt;?php

namespace Drupal\my_module\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;

class MyClass implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['my404Check'];

    return $events;
  }

  public function my404Check(GetResponseEvent $event) {
    // Do some logic here to check if it should be a 404.
    throw new NotFoundHttpException();
  }

}


I'm guessing I can't throw exceptions here, but can't see any other documentation on how to issue the 404.
You can set a response early in a request event: 

 public function my404Check(GetResponseEvent $event) {

    // only return a response for a master request
    if (!$event-&gt;isMasterRequest()) {
      return;
    }

    // Do some logic here to check if it should be a 404.

    $response = new Response('', Response::HTTP_NOT_FOUND);
    $event-&gt;setResponse($response);
  }


The event dispatcher checks if a response is already set and returns this response without executing any more code to build a Drupal response.