Skip to content

Instantly share code, notes, and snippets.

@rattfieldnz
Last active August 26, 2017 09:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rattfieldnz/057df7f9cee6afa367c0b116d3156c6f to your computer and use it in GitHub Desktop.
Save rattfieldnz/057df7f9cee6afa367c0b116d3156c6f to your computer and use it in GitHub Desktop.
Return a Google_Service_Exception as a collection (good for API usage with Laravel framework)
/**
* Return a Google_Service_Exception as a collection (good for API usage with Laravel framework).
*
* This example is used in a Laravel (v 5.4.34) app with spatie/analytics package.
*
* @param \Google_Service_Exception $e
*
* @see https://github.com/spatie/laravel-analytics
* @see https://github.com/google/google-api-php-client/blob/master/src/Google/Service/Exception.php
* @see https://developers.google.com/analytics/devguides/reporting/core/v3/errors
* @see https://github.com/laravel/framework/blob/5.4/src/Illuminate/Support/Collection.php
*
* @return \Illuminate\Support\Collection
*/
public static function googleException(Google_Service_Exception $e): Collection{
$status = "error";
$alternativeException = collect([
'status' => $status,
'code' => 500,
'reason' => 'unknown',
'message' => "There is an issue with your usage of Google Analytics API - this has been logged to your app and server logs."
]);
Log::error($e->getMessage());
if($e instanceof \Google_Service_Exception && !empty($e)){
$errorException = json_decode($e->getMessage())->error;
if(!empty($errorException) && !empty($errorException->errors[0])){
$reason = $errorException->errors[0]->reason;
$message = $errorException->errors[0]->message;
$code = $errorException->code;
return collect(
[
'status' => $status,
'code' => $code,
'reason' => $reason,
'message' => $message . " This has been logged to your app logs."
]
);
} else {
return $alternativeException;
}
} else{
return $alternativeException;
}
}
@rattfieldnz
Copy link
Author

Supplemental information about Google Analytics API errors @ https://developers.google.com/analytics/devguides/reporting/core/v3/errors.

NOTE: This might not be suitable for v4 of the API - feel free to make suggestions on compatibility if needed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment