So I just started using the slim PHP Framework and I'm a bit confused. As stated in the documentation: https://www.slimframework.com/docs/v4/middleware/error-handling.html#adding-custom-error-handlers
This should add some sort of Error Handling.
So I tested that code:
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Psr\Log\LoggerInterface;
require __DIR__ . '/vendor/autoload.php';
$app = AppFactory::create();
// Add Routing Middleware
$app->addRoutingMiddleware();
// Define Custom Error Handler
$customErrorHandler = function (
Request $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails,
?LoggerInterface $logger = null
) use ($app) {
$logger->error($exception->getMessage());
$payload = ['error' => $exception->getMessage()];
$response = $app->getResponseFactory()->createResponse();
$response->getBody()->write(
json_encode($payload, JSON_UNESCAPED_UNICODE)
);
return $response;
};
// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
$errorMiddleware->setDefaultErrorHandler($customErrorHandler);
$app->get('/', function (Request $request, Response $response, $args) {
$test = [];
$foo = $test['nada'];
$response->getBody()->write("Hello world!");
return $response;
});
$app->run();
Now when I either call an undefined Route such as
localhost:8000/this/route/doenst/exist
or just simply let some faulty code run (accessing an undefined key from array)
localhost:8000/
I just get the "plain" Error
So I guess my question is: How can i implement an error Handler that handles coding errors or calling to undefined routes?
The ErrorMiddleware
handles any type of Exception
or Throwable
.
You can test the ErrorMiddleware by throwing an Exception as follows:
throw new \RuntimeException('Test error message');
Besides Throwable
PHP has its older error level system of warnings, notices and errors.
Undefined index in index.php line 42
is just an PHP notice.
The Slim ErrorMiddleware does not handle this type of PHP errors.
To “catch” this type of PHP error, you can add a custom error handler using the set_error_handler
function or you may add the Symfony ErrorHandler component, which provides tools for managing this kind of errors.
composer require symfony/error-handler
Add a custom middleware:
// Throw an exception when a PHP error occurs
// and handled it with the Slim error handler.
ErrorHandler::register();
return $handler->handle($request);
Read more