im trying to handdle request status code, basically checking if the status is 200, in case that it isnt handle it. Im using a package called "GuzzleHttp\Client", when there is a 404 it gives me a error:
Client error: `GET https://api.someurl---` resulted in a `404 Not Found` response:
{"generated_at":"2017-09-01T16:59:25+00:00","schema":"","message":"No events scheduled for this date."}
But than in the screen is displayed in a format that i want to change, so im trying to catch and give a different output on the view. But is not working, it stills gives me the red screen error.
try {
$client = new \GuzzleHttp\Client();
$request = $client->request('GET', $url);
$status = $request->getStatusCode();
if($status == 200){
return $status;
}else{
throw new \Exception('Failed');
}
} catch (\GuzzleHttp\Exception\ConnectException $e) {
//Catch errors
return $e->getStatusCode();
}
Okay so if you want to stick with a try-catch you want to do something like this:
$client = new \GuzzleHttp\Client();
try {
$request = $client->request('GET', $url);
} catch (\GuzzleHttp\Exception\ConnectException $e) {
// This is will catch all connection timeouts
// Handle accordinly
} catch (\GuzzleHttp\Exception\ClientException $e) {
// This will catch all 400 level errors.
return $e->getResponse()->getStatusCode();
}
$status = $request->getStatusCode();
If the catch doesn't get triggered the $request
would be successful meaning it'll have a status code of 200.
However to to catch the 400 error, ensure you've got http_errors
request option is set to true when setting up the $client
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With