php - How to handle multiple api calls on a background job laravel
I have a background job firing api calls to google and facebook api's I know margin on failure for those api's its really slim, but due to the fact that my app depends on the data I get from those calls I want to make sure that my app doesnt get stuck when api call fails:
public function handle()
{
try {
$googleService = new GoogleClient;
$data = $googleService->report()
->from('AD_PERFORMANCE_REPORT')
->during('20170101', '20170126')
->select('
Impressions, CampaignId, Clicks, Ctr,Cost, AverageCost, Interactions, Conversions, Status, Id')
->getObject();
$this->transform->response($data->result);
$client = new FacebookClient;
$response = $client->insights()->select("impressions, ad_id, clicks,ctr, cpc,campaign_name ")->during('2013-01-01', '2018-01-31')->where(['accountid' => 'act_1222222'])->get();
$this->transform->response($response);
} catch (Exception $e) {
}
}
I have done research on how to handle jobs when an api call fails, non of them helped.
So my question is: What is the best way to handle the situation when an api call fails, In case one of them fails then I want to log the failure and keep the worker going ?
Answer
Solution:
You can use Laravel Queues to accomplish such tasks.
From Laravel's official site.
Answer
Solution:
If your api call fails but your application depends on that response, you should try to retry the call again and again, until you get a proper response, you can probably use a timeout between requests too so you don't get the
Too Many Requests
response.If your api call fails and your application doesn't depend on the response you can just use a logger and log the error in your file and either retry the call, or just skip it and continue.
But I agree with @Amit Merchant you should go with Laravel Queues
Answer
Solution:
Laravel has some interesting helper functions that you should look into. Of particular interest would be the retry function. Just as it implies, it retries the execution of anything in the callback until either A) no exception is thrown, or B) the maximum threshold it reached.
Simply wrap your api call and specify a limit before handling a failed state.
Example from the docs: