You don't want to override the exception messages when they are thrown in routing or elsewhere. Better use an exception handler to catch all JSON 404 exceptions:
/src/EventSubscriber/MymoduleExceptionSubscriber.php
<?php
namespace Drupal\mymodule\EventSubscriber;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
class MymoduleExceptionSubscriber extends HttpExceptionSubscriberBase {
protected static function getPriority() {
// handle the exceptions we want for JSON before
// core subscribers do this with priority -70/-75
return -69;
}
protected function getHandledFormats() {
return ['json'];
}
public function on404(ExceptionEvent $event) {
/** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
$exception = $event->getThrowable();
$content = [
'code' => 60,
'message' => 'Resource not found',
'description' => 'The requested URI or the requested resource does not exist.',
];
// If the exception is cacheable, generate a cacheable response.
if ($exception instanceof CacheableDependencyInterface) {
$response = new CacheableJsonResponse($content, 404, $exception->getHeaders());
$response->addCacheableDependency($exception);
}
else {
$response = new JsonResponse($content, 404, $exception->getHeaders());
}
$event->setResponse($response);
}
}
mymodule.services.yml
services:
mymodule.404_subscriber:
class: Drupal\mymodule\EventSubscriber\MymoduleExceptionSubscriber
tags:
- { name: event_subscriber }
web/core/modules/rest/tests/src/Functional/EntityResource/EntityResourceTestBase.php
core/modules/rest/tests/src/Functional/EntityResource/EntityResourceTestBase.php
is test code.vendor/symfony/http-kernel/EventListener/RouterListener.php
. So the question is how to override Symfony class/method I guess!core/modules/workspaces/src/EventSubscriber/WorkspaceRequestSubscriber.php
is an example of overriding that listener.