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.