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 ofException
orThrowable
.You can test the ErrorMiddleware by throwing an Exception as follows:
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.Add a custom middleware:
Read more