Catching a 401 response in Symfony [duplicate]

Solution 1:

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
}

By default, if the client response is in the 3xx-5xx range, and you call getHeaders, getContent or toArray (as you were doing) then an HTTPExceptionInterface exception gets thrown. You can choose to try and catch that exception, or alternatively, you can still call those methods by passing an optional false value as a parameter.

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