2

I want to change the page not found error message.

Recently, message shows like The requested page could not be found. I want to show The requested page "/nvzmx,nvm,zxnv," could not be found.

I don't want to create a custom page. I only want to change the error message given in the page not found page.

3
  • If you want custom page for "page not found" then create an new basic page with content that you want. After that set that newly created node in admin/config/system/site-information settings in ERROR PAGES section "Default 404 (not found) page". Oct 18, 2016 at 6:04
  • Thanks For quick reply I know that but I want change my page not found message. Oct 18, 2016 at 6:17
  • And that's exactly what you can do with this approach. The 404 message isn't just a message, it is a page. And you can configure it to use any node, on which you can then have whatever message/content you want.
    – Berdir
    Oct 23, 2016 at 12:19

1 Answer 1

3

You can do this by overwriting the route system.404 with a custom controller:

mymodule/src/Controller/MyHttp4xxController.php

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyHttp4xxController extends ControllerBase {

  public function on404() {
    return [
      '#markup' => $this->t('Custom 404 message'),
    ];
  }

mymodule.routing.yml

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

mymodule.install

<?php

function mymodule_install() {
  module_set_weight('mymodule', 1);
}

You have to be sure, that your module runs after the system module, so that you can overwrite the route from the system module. This is why you need to set the module weight to 1. You need to reinstall the module, when you implement this.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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