Attention

TYPO3 v9 has reached its end-of-life September 30th, 2021 and is not maintained by the community anymore. Looking for a stable version? Use the version switch on the top left.

You can order Extended Long Term Support (ELTS) here: TYPO3 ELTS.

Writing a Custom Page Error Handler

The error handling configuration for sites allows implementing a custom error handler if the existing options of rendering a fluid template or page are not enough. An example would be an error page that uses the requested page or its parameters to search for relevant content on the web site.

A custom error handler needs to have a constructor that takes exactly two arguments:

  • $statusCode: an integer holding the status code TYPO3 expects the handler to use

  • $configuration: an array holding the configuration of the handler

Furthermore it needs to implement the PageErrorHandlerInterface (\TYPO3\CMS\Core\Error\PageErrorHandler\PageErrorHandlerInterface). The interface specifies only one method: handlePageError(ServerRequestInterface $request, string $message, array $reasons = []): ResponseInterface

Let's take a closer look:

The method handlePageError get's three parameters:

  • $request: the current HTTP request - we can for example access query parameters and the request path via this object

  • $message: an error message string - for example Cannot connect to the configured database. or Page not found

  • $reasons: an arbitrary array of failure reasons - see for example \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageAccessFailureReasons

What you do with these variables is left to you, but you need to return a valid ResponseInterface response - most usually an HtmlResponse.

For an example implementation of the PageErrorHandlerInterface take a look at \TYPO3\CMS\Core\Error\PageErrorHandler\PageContentErrorHandler or \TYPO3\CMS\Core\Error\PageErrorHandler\FluidPageErrorHandler.

Examples

Example for a simple 404 ErrorHandler

The configuration in config.yaml:

errorHandling:
   -
      errorCode: '404'
      errorHandler: PHP
      errorPhpClassFQCN: My\ExtensionName\Error\ErrorHandling

The ErrorHandler class:

<?php

namespace My\ExtensionName\Error;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Error\PageErrorHandler\PageErrorHandlerInterface;
use TYPO3\CMS\Core\Http\RedirectResponse;

class ErrorHandling implements PageErrorHandlerInterface
{

    /**
     * @param ServerRequestInterface $request
     * @param string $message
     * @param array $reasons
     * @return ResponseInterface
     */
    public function handlePageError(
        ServerRequestInterface $request,
        string $message,
        array $reasons = []
    ): ResponseInterface {
           return new RedirectResponse('/404-page', 404);
    }

}