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->isMasterRequest()) {
return;
}
// Do some logic here to check if it should be a 404.
$response = new Response('', Response::HTTP_NOT_FOUND);
$event->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.