Joshua Dalley
Joshua Dalley

Reputation: 339

Silex - my error handler isn't working

I am trying to set up a error handler on my controller to catch anything that might cause my page to malfunction. For example: in this scenario I am trying to catch any error that could possibly happen once my method calls a external API with a bad parameter but it doesn't seem to do anything except give me the typical ClientException in Middleware.php line 69: Client error: 400 which isn't what I am exactly aiming for. Any advice will be greatly be appreciated or better ways of handling errors in Silex.

private function getSIS($url, $session, Application $app)
{
    $message = "You don't have permission to access this!";

    if($app['security']->isGranted('ROLE_SUPER_ADMIN'))
    {
        $client = new Client(['base_uri' => 'https://***********.ca/api/SIS/']);
        if (!empty($session))
            $response = $client->get($url, ['query' => 'session=' . $session]);
        else
            $response = $client->get($url);
        return $response;
    }

    $app->error(function (\Exception $e, $code) {
        switch($code) {
            case 404:
                $message = 'The requested page could not be found';
                break;
            default:
                $message = 'We are sorry, but something went terribly wrong.';
        }

        return new Response($message);
    });

    return new Response($message);
}

Upvotes: 1

Views: 348

Answers (1)

ooXei1sh
ooXei1sh

Reputation: 3559

The $app->error method might need to be placed outside the context of your controller actions. I'm not sure exactly how you have your application structured but maybe try placing the error block right before $app->run();

$app->error(function (\Exception $e, $code) use ($app) {
    switch($code) {
        case 404:
            $message = 'The requested page could not be found';
            break;
        default:
            $message = 'We are sorry, but something went terribly wrong.';
    }

    return new Response($message, $code);
});

$app->run();

Upvotes: 2

Related Questions