在 Symfony 中捕获 401 响应

Catching a 401 response in Symfony

我正在尝试在 Symfony 应用程序 (6.0) 中自定义错误响应。 该应用使用 oauth 令牌交换使用 http 客户端向外部 API 发出请求。如果令牌无效,API 会给出 401 响应

    protected function request(string $token, string $url, array $query): array
    {
        //Create a new client
        $httpClient = HttpClient::create(['base_uri' => self::API_URL]);
        //Set up request headers
        $headers = [
            'Authorization' => 'Bearer ' . $token,
            'Content-type' => 'application/json'
        ];
        //Get response
        $response = $httpClient->request('GET', $url, [
            'headers' => $headers,
            'query' => $query,
        ]);
        //Return the body of the response object as an array
        return $response->toArray();
    }

当使用无效令牌对此进行测试时,它会导致抛出类型为 ClientException 的异常,这会产生 HTTP 500 内部服务器错误和消息:

HTTP/2 401 returned for "https://www.strava.com/api/v3/athlete".

我希望捕获此错误并显示有关如何使用 https://symfony.com/doc/current/controller/error_pages.html 中描述的方法修复它的信息。我认为这是一个 401 错误,我可以在名为 error401.html.twig.

的页面中捕获它

我的问题是为什么将此错误视为 500 而不是 401?

您反映的正是您的 http 客户端接收到的内容。您应该检查响应代码和 return 站点响应所需的内容,而不是仅仅重复客户端响应中的所有数据。

$statusCode = $response->getStatusCode();
if (401 === $statusCode) {
    // set your response as desired
    
}
if (200 === $statusCode) {
    // set your response as desired
}

默认情况下,如果客户端响应在 3xx-5xx 范围内,并且您调用 getHeaders、getContent 或 toArray(正如您所做的那样),则会抛出 HTTPExceptionInterface 异常。您可以选择尝试捕获该异常,或者您仍然可以通过将可选的 false 值作为参数传递来调用这些方法。

$clientResponseData = $response->toArray(false);