Themes are easiest to be set via the Controller.beforeRender
event, or for earlier CakePHP versions, via the Controller::$theme
property.
The default exception renderer uses a new controller instance for handling errors, therefore you can for example
Create a custom error controller and add a listener/callback
One option would be to create a custom error controller where you can set the theme as you would in a regular controller. By default CakePHP will use \App\Controller\ErrorController
if it exists, so all you'd need to do would be to create the controller.
src/Controller/ErrorController.php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
class ErrorController extends Controller
{
public function beforeRender(Event $event)
{
$this->viewBuilder()->theme('ErrorThemeName');
}
}
Done, all exceptions should now use the ErrorThemeName
theme.
See also
Create a custom exception renderer and add a listener to the controller
You could also create a custom/extended exception renderer, and override ExceptionRenderer::_getController()
, and add a proper listener for the Controller.beforeRender
where you can set the theme.
src/Error/AppExceptionRenderer.php
namespace App\Error;
use Cake\Error\ExceptionRenderer;
use Cake\Event\Event;
class AppExceptionRenderer extends ExceptionRenderer
{
protected function _getController()
{
$controller = parent::_getController();
$controller->eventManager()->on('Controller.beforeRender', function (Event $event) {
$event->subject()->viewBuilder()->theme('ErrorThemeName');
});
return $controller;
}
}
config/app.php
// ...
'Error' => [
'exceptionRenderer' => '\App\Error\AppExceptionRenderer',
// ...
],
// ...
See also
Cookbook > Error & Exception Handling > Using the exceptionRenderer Option of the Default Handler