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?