jordankaiser
1/23/2019 - 7:48 PM

Custom Error Page Programitcally

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Get Request Object.
  $request = \Drupal::request();

  // If there is HTTP Exception..
  if ($exception = $request->attributes->get('exception')) {
    // Get the status code.
    $status_code = $exception->getStatusCode();
    if (in_array($status_code, array(401, 403, 404))) {
      $suggestions[] = 'page__' . $status_code;
    }
  }
}

Drupal 8 programtic custom error page

This is for Drupal 8.

The snippet was taken from axelerant.com.

Basically we're feeding drupal a theme hook suggestion if there is an HTTP error.

The snippet was one of two suggestions. The other one follows.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $route_name = \Drupal::routeMatch()->getRouteName();
  switch ($route_name) {
    case 'system.401':
      // Unauthorized Access.
      $error = 401;
      break;

    case 'system.403':
      // Access Denied.
      $error = 403;
      break;

    case 'system.404':
      // Page Not Found.
      $error = 404;
      break;
  }
  if (isset($error)) {
    $suggestions[] = 'page__' . $error;
  }
}