Customizing HTTP Error Pages In Drupal 8

Tags: Drupal 8, HTTP


In the web development world, developers often come across situations where site owners complain about the simplicity of HTTP error pages (Access Denied, Page Not Found, etc) that are shown to end users, especially when business competitors are being very creative in the development and design of the HTTP error pages. Take a look at these 404 pages for an idea of how beautiful they can look. Also check out this HTTP 404 page from Google.

This is true for Drupal as well, as Drupal’s error pages are very simple and to the point. However, Drupal addresses the end-user’s requirements quite well, allowing site builders and developers to customize these error pages out of the box. Along with that, it also provides ways to alter these pages.

Let’s get into the core of customizing these pages.

The Basics

We really need to focus on the word ‘Page’ in the term ‘HTTP error page’. Because an HTTP error page is always a ‘page’. Period!

In Drupal, It can be a Node page, View Page Display, Panel page, Custom Route (URL), etc.

Out Of The Box

Drupal creates some custom Routes (URLs) in the system.routing.yml file

system.401:
  path: '/system/401'
  defaults:
    _controller: '\Drupal\system\Controller\Http4xxController:on401'
    _title: 'Unauthorized'
  requirements:
    _access: 'TRUE'

system.403:
  path: '/system/403'
  defaults:
    _controller: '\Drupal\system\Controller\Http4xxController:on403'
    _title: 'Access denied'
  requirements:
    _access: 'TRUE'

system.404:
  path: '/system/404'
  defaults:
    _controller: '\Drupal\system\Controller\Http4xxController:on404'
    _title: 'Page not found'
  requirements:
    _access: 'TRUE'


The above routes create error markups which are rendered whenever a user tries to access pages on the site which either don’t exist or are not authorized to be accessed by users.

class Http4xxController extends ControllerBase {

  /**
   * The default 401 content.
   *
   * @return array
   *   A render array containing the message to display for 401 pages.
   */
  public function on401() {
    return [
      '#markup' => $this->t('Please log in to access this page.'),
    ];
  }

  /**
   * The default 403 content.
   *
   * @return array
   *   A render array containing the message to display for 403 pages.
   */
  public function on403() {
    return [
      '#markup' => $this->t('You are not authorized to access this page.'),
    ];
  }

  /**
   * The default 404 content.
   *
   * @return array
   *   A render array containing the message to display for 404 pages.
   */
  public function on404() {
    return [
      '#markup' => $this->t('The requested page could not be found.'),
    ];
  }

}

 

So this is how Drupal creates ‘Page Not Found’ and ‘Access Denied’ errors out-of-the-box.

Customizing Error Messages

What Drupal provides out-of-the-box is quite simple, and this is the reason it also offers ways by which you can alter error pages and show your creativity.

In this post, we will see two methods by which we can change the error messages/pages:

Method 1: The Drupal Configuration method

First of all, we need to create a page. To do that, follow the steps below:

  • Log in to your Drupal site as administrator.
  • Create a content type called ‘error pages’. (Optional: You can use an existing one as well).
  • Create a node page with ‘error pages’ content type. This node page will act as our error page. (Remember the idea of error messages being basically a page?)
  • Add the content and style it as per your requirements.

Now, we need to use the node page as our error page. To do that, follow the steps below:

  • Log in to your Drupal site as administrator.
  • Go to url ‘/admin/config/system/site-information’.
  • Under the Error Pages section of the above URL, mention your new node page URL.

1

That’s it, you just configured the error pages via the Drupal UI, where the content of error pages will be determined by how you have configured your Node Content.

Method 2: The Programmatic Method

Apart from configuring the error pages from the Drupal UI, we can use ‘hook_theme_suggestions_HOOK_alter()’ and suggest TWIG templates to Drupal against the error pages. Let’s see how we can do that:

  1. Implement a ‘hook_theme_suggestions_HOOK_alter()’ in your theme file.
  2. This hook will catch error messages and tell Drupal to use a TWIG against this error page.
  3. Place the error-specific TWIG file in your theme’s template directory.

I am listing two ways/functions below by which we can suggest error-specific TWIG templates to Drupal. (If you know of more ways to catch these errors, do share your thoughts in the comments.)

Function 1:

/**
 * 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;
  }
}


Function 2:

<?
/**
 * 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;
    }
  }
}

 
The next step after adding one of the above functions to your code is to add the TWIG templates to your theme and format the HTML in it.

So this is how Drupal allows us to configure HTTP error pages via configuration and code. And the smart move for you will be to not wait any more and jump into revamping your HTTP error pages, showing your competitors how creative you can be.

Kunal Kursija, Back-end Developer
Posted on Feb 15, 2018 4:32:26 AM by

Kunal Kursija, Back-end Developer