Saturday, May 12, 2018

How to manually catch error exception in Laravel - development

How to manually catch error exception in Laravel

In my project i need to do a bulk import and data insertion in the database.

So, I needed to know that when a API request is failed. Here, the problem is that PHP unable to catch that exception because Laravel 5.6 would stop the execution while there is any kind of error.

I needed to stop laravel from automatically stop the execution and let php decide that if an API request failed then lets wait 5 second and try again.

To achieve this i have made a function inside a laravel controller.

private function fetchAPI($id) {
    try {
        $rawResult = file_get_contents('http://example.com/'.$id.'?key=5453');
    } catch (Exception $e) {
        sleep(5);
        $this->fetchAPI($id);
    }
    return json_decode($rawResult, true);
}

The above method will utilize the try…catch block. But i have also implemented with a boolean check with no luck:

private function fetchAPI($id) {
    $rawResult = file_get_contents('http://example.com/'.$id.'?key=5453');
    if($rawResult === FALSE) {
        sleep(5);
        $this->fetchAPI($id);
    } else {
        return json_decode($rawResult, true);
    }
}

In this scenario how i can re-try if API request failed from a Laravel controller method?



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-manually-catch-error-exception-in-laravel/
via Lzo Media

No comments:

Post a Comment