Home > Software engineering >  Catching a 401 response in Symfony
Catching a 401 response in Symfony

Time:01-19

I am trying to customise the error responses in a Symfony app (6.0). The app makes as request using http client to an external API using an oauth token exchange. If the token is not valid the API gives a 401 response

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

When is test this with an invalid token it causes an exception to be thrown of type ClientException and this gives a HTTP 500 Internal Server Error with the message:

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

I was hoping to catch this error and display information on how to fix it using the methods described on https://symfony.com/doc/current/controller/error_pages.html. I thought that as it was a 401 error I could catch it in a page called error401.html.twig.

My question is why is this error treated as a 500 rather than a 401? Can you point me to some reading where I can understand this better.

Thanks in advance for assistance.

CodePudding user response:

You are reflecting back exactly what your http client is receiving. You should check the response code and return what you need for your site response rather than just regurgitating all the data from the client response.

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