Silex - 我的错误处理程序不工作

Silex - my error handler isn't working

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

$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();