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 website.
A custom error handler needs to have a constructor that takes exactly two arguments:
$status
: an integer holding the status code TYPO3 expects the handler to useCode $configuration
: an array holding the configuration of the handler
Furthermore it needs to implement the Page
(EXT:core/Classes/Error/PageErrorHandler/PageErrorHandlerInterface.php (GitHub)).
The interface specifies only one method:
handle
Let us take a closer look:
The method handle
gets three parameters:
$request
: the current HTTP request - for example, we can 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 EXT:frontend/Classes/Page/PageAccessFailureReasons.php (GitHub)
What you do with these variables is left to you, but you need to return a
valid \Psr\
response - most usually an
\TYPO3\
.
For an example implementation of the Page
, take a
look at EXT:core/Classes/Error/PageErrorHandler/PageContentErrorHandler.php (GitHub)
or EXT:core/Classes/Error/PageErrorHandler/FluidPageErrorHandler.php (GitHub).
For a custom 403 error handler with redirect to a login form, please see Custom error handler implementation for 403 redirects.
Properties
The custom error handlers have the properties Properties and Properties and the following:
- errorPhpClassFQCN
-
- type
-
string
- Example
-
\My
Vendor\ My Site Package\ Error\ My Error Handler
Fully-qualified class name of a custom error handler implementing
Page
.Error Handler Interface
Example for a simple 404 error handler
The configuration:
errorHandling:
- errorCode: '404'
errorHandler: PHP
errorPhpClassFQCN: MyVendor\MySitePackage\Error\MyErrorHandler
The error handler class:
<?php
declare(strict_types=1);
namespace MyVendor\MySitePackage\Error;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Error\PageErrorHandler\PageErrorHandlerInterface;
use TYPO3\CMS\Core\Http\HtmlResponse;
final class ErrorHandler implements PageErrorHandlerInterface
{
private int $statusCode;
private array $errorHandlerConfiguration;
public function __construct(int $statusCode, array $configuration)
{
$this->statusCode = $statusCode;
// This contains the configuration of the error handler which is
// set in site configuration - this example does not use it.
$this->errorHandlerConfiguration = $configuration;
}
public function handlePageError(
ServerRequestInterface $request,
string $message,
array $reasons = [],
): ResponseInterface {
return new HtmlResponse('<h1>Not found, sorry</h1>', $this->statusCode);
}
}