Drupal Do Something on 404 and 403

Last modified: 
Tuesday, April 5th, 2016

This is an example of implementing hook_page_build() to run an arbitrary function on 404 and 403 pages. I used hook_page_build() here, because the HTTP header status wasn't reliably available in previous hook calls.

/**
 * Makes sure _MYMODULE_function() runs on 404 and 403 pages
 * for anonymous users. 
 */
function MYMODULE_page_build(&$page) {
  if (user_is_anonymous()) {
    $status = drupal_get_http_header('Status');
    if ('404 Not Found' === $status || '403 Forbidden' === $status) {
      _MYMODULE_function();
    }
  }
}


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.