Silex - 我的错误处理程序无法运行

时间:2015-09-04 18:08:09

标签: symfony error-handling silex

我正在尝试在我的控制器上设置错误处理程序,以捕获可能导致我的页面出现故障的任何内容。例如:在这种情况下,我试图捕获任何可能发生的错误,一旦我的方法调用带有错误参数的外部API但它似乎没有做任何事情,除了给我典型的ClientException in Middleware.php line 69: Client error: 400 isn'我正是为了什么。任何建议都将受到极大的赞赏,或者更好的方法来处理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);
}

1 个答案:

答案 0 :(得分:1)

$app->error方法可能需要置于控制器操作的上下文之外。我不确定您的应用程序是如何构建的,但可能会尝试在$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();