Google News
logo
Slim Framework - Interview Questions
What about Error Handling/Rendering in Slim Framework?
The rendering is finally decoupled from the handling. It will still detect the content-type and render things appropriately with the help of ErrorRenderers. The core ErrorHandler extends the AbstractErrorHandler class which has been completely refactored. By default it will call the appropriate ErrorRenderer for the supported content types. The core ErrorHandler defines renderers for the following content types :
 
* application/json
* application/xml and text/xml
* text/html
* text/plain

For any content type you can register your own error renderer. So first define a new error renderer that implements \Slim\Interfaces\ErrorRendererInterface.
<?php
use Slim\Interfaces\ErrorRendererInterface;
use Throwable;

class MyCustomErrorRenderer implements ErrorRendererInterface
{
    public function __invoke(Throwable $exception, bool $displayErrorDetails): string
    {
        return 'My awesome format';
    }
}
And then register that error renderer in the core error handler. In the example below we will register the renderer to be used for text/html content types.
<?php
use MyApp\Handlers\MyErrorHandler;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

// Add Routing Middleware
$app->addRoutingMiddleware();

// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware(true, true, true);

// Get the default error handler and register my custom error renderer.
$errorHandler = $errorMiddleware->getDefaultErrorHandler();
$errorHandler->registerErrorRenderer('text/html', MyCustomErrorRenderer::class);

// ...

$app->run();
Advertisement