0

Same question as a few years back for Drupal7 - but the offline maintenance page seems a little different in Drupal 8/9/10 - and still a work in progress:

https://www.drupal.org/project/drupal/issues/2720109

We have Cloudflare sitting in front of our Drupal sites - and in order to take advantage of their "AlwaysOnline" feature - we need to alter the response code sent in the event of an error - we need a 504 code.

I want to cater for when the database is unavailable - as this can sometimes happen when upgrading the MySQL server.

I did this in Drupal 7 using:

function MYTHEME_preprocess_maintenance_page(&$variables) {
  drupal_add_http_header('Status', '504 Service unavailable (with message)');
}

How do we alter the response code in Drupal 9 when the database connection is down without hacking core?

1
  • I think event listeners might be called for error pages - maybe you could create an event listener with a higher priority than the one that throws the error page, and add the header there.
    – Jaypan
    Jan 24 at 16:18

1 Answer 1

0

As @Jaypan commented, normally you are able to catch database exceptions in a Symfony event subscriber, but Drupal has made the bootstrap process depending on the database before Symfony could even load the container. The only non-core files available so early are in the sites folder. Modules are not initialized at this point.

To catch database exceptions during the bootstrap process put this PHP file in the sites folder:

/sites/exception.inc

<?php

use Drupal\Core\Database\DatabaseException;
use Symfony\Component\HttpFoundation\Response;

function _db_exception_handler($exception) {
  if ($exception instanceof \PDOException || $exception instanceof DatabaseException) {
    $response = new Response('Service not available!', 504);
    $response->send();
    exit;
  }
  _drupal_exception_handler($exception);
}

set_exception_handler('_db_exception_handler');

and this line in settings.php:

include DRUPAL_ROOT . '/sites/exception.inc';
2
  • Thanks for this - great concept. Would you expect this to override the general exception handling of Drupal for database errors seen with the framework? Ideally - I need some form of getting down to just the maintenance page offline situation. I'll give it a try - thanks! Jan 26 at 16:02
  • This is only for the boostrap process and here we call the original _drupal_exception_handler when we don't want to catch the exception. After that the framework handles exceptions like in this example drupal.stackexchange.com/questions/235906/…
    – 4uk4
    Jan 26 at 17:24

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.