php - Access Laravel HTTP client status code in catch block
Solution:
You can get the estimated time the request was being transferred by the handler via :
$response = Http::withHeaders(['User-Agent' => 'Mozilla/5.0+(compatible; DomainMonitor/2.0; https://domain-monitor.io/)'])
->timeout($timeout)
->get($url);
$responseTime = $response->transferStats->getTransferTime();
$return = [
'response_time' => round($responseTime),
'code' => $response->getStatusCode(),
'ok' => $response->successful(),
'json' => $response->json(),
'headers' => $response->headers()
];
FYI, unlike Guzzle's default behavior, Laravel's HTTP client wrapper does not throw exceptions on client or server errors (400
and 500
level responses from servers). So, you don't need to make a try-catch
. You may determine if one of these errors was returned using the successful
, clientError
, or serverError
methods.
Answer
Solution:
Try this way
try {
$startResponseTime = microtime(true);
$response = Http::withHeaders([
'User-Agent' => 'Mozilla/5.0+(compatible; DomainMonitor/2.0; https://domain-monitor.io/)'
])->timeout($timeout)->get($url);
$stopResponseTime = microtime(true);
$responseTime = ($stopResponseTime - $startResponseTime) * 1000;
if($response->successful()){
return [
'response_time' => round($responseTime),
'code' => $response->getStatusCode(),
'ok' => $response->ok(),
'json' => $response->json(),
'headers' => $response->headers()
];
}else{
return [
'response_time' => round($responseTime),
'code' => $response->getStatusCode(),
'ok' => false,
'json' => null,
'headers' => null
];
}
} catch (\Exception $e) {
return [
'response_time' => 0,
'code' => 0,
'ok' => false,
'json' => null,
'headers' => null,
'message' => $e->getMessage(), //get exception message
];
}
Source