I want to check the status code of a page. I have tried with the following code in hook_preprocess_page(), but it doesn't work.

$status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception'); 
$status = \Drupal::request()->attributes->get('_route');
if ('system.404' === $route_name) {
  // Omissis.

How can I check the status code for a page?


If the goal is to act when Drupal returns 404, 403 etc responses, you should use an event subscriber.

Symfony has events for various things, you could use the HttpExceptionSubscriberBase as base for exception handling which is how 404 and 403 responses are created. You can take a look at DefaultExceptionHtmlSubscriber for how this is done.

You could also create a custom event suscriber and listen for the KernelEvents::RESPONSE, where you can do whatever based on the response being generated by Drupal.

  • Thanks for your reply.How can i use DefaultExceptionHtmlSubscriber and KernelEvents::RESPONSE events to check the status?I have little knowledge with drupal8 and symfony. – Daisy Mol Sep 17 '18 at 5:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.