Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel catch error before laravel does

I am using Laravel 5.1 and Guzzle to send API requests.

I have two functions, one to get a person, and the second one to retrieve data about the person, as each one is a separate request.

If the is nothing found for either a 404 response code is sent back and picked up by laravel.

However the 404 response from function 1 has a different meaning than the response from function two, even though they are the same response code and exception but guzzle.

i have tried to catch the error in the controller for the method in hope that it will catch it before laravels exception handler does, but it does not seem to work and get caught by the handler.

how can i catch the Exception in the controller before Laravels Exception handler?

like image 563
Josh Kirkpatrick Avatar asked Feb 10 '23 16:02

Josh Kirkpatrick


1 Answers

In the top of the Controller add:

use GuzzleHttp\Exception\RequestException;

Wrap your request in a try catch like so:

try {
    $client->get('https://github.com/_abc_123_404');
} catch (RequestException $e) {
    echo $e->getRequest();
    if ($e->hasResponse()) {
        echo $e->getResponse();
    }
}

You can catch any Guzzle exception, if you want to only catch 404, then you could try to use ClientException in the top of your controller, and catch that, this exception extends BadResponseException which in turn extends RequestException. See the documentation for more detail.

like image 100
Francesco de Guytenaere Avatar answered Feb 12 '23 15:02

Francesco de Guytenaere