Error handling and getting a name

  1. How to handle errors 404, 500, 409 etc.?
    In version 3, this happened through containers. How about 3?
    So in version 3:
$c = new \Slim\Container();

$c['notFoundHandler'] = function ($c) {
    return function ($request, $response) use ($c) {
        return $response->withStatus(404)
            ->withHeader('Content-Type', 'text/html')
            ->write('Page not found');
    };
};

$app = new \Slim\App($c);

How about 4?

  1. And does anyone know how to get the name of the router that was executed?
    For example:
    $app->get('/', Home::class . ':get')->setName('home');

And I need to get a name

Hi @unnamed123

  1. I’m sure you’ll find the answer here :slight_smile:
    http://www.slimframework.com/docs/v4/middleware/error-handling.html

  2. Try this:

$routeName = \Slim\Routing\RouteContext::fromRequest($request)->getRoute()->getName();
1 Like

Thanks!

I want to use RouteContex :: fromRequest () in the middleware, but the error is:

Fatal error: Uncaught RuntimeException: Cannot create RouteContext before routing has been completed in G:\Program\OSPanel\domains\Slim4\vendor\slim\slim\Slim\Routing\RouteContext.php on line  *30*
RuntimeException: Cannot create RouteContext before routing has been completed in G:\Program\OSPanel\domains\Slim4\vendor\slim\slim\Slim\Routing\RouteContext.php on line  *30*

How to fix it?

Then make sure that you have added the RoutingMiddleware:

$app = AppFactory::create();

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

// ...

$app->run();
1 Like