PHP - Cannot catch exception thrown by Google API API

I want to get an exception that is thrown by the Google API by the PHP library , but for some reason throws a "Fatal Error: Unrecoverable exception" before reaching my catch block.

In my application, I have something like this:

try { $google_client->authenticate($auth_code); } catch (Exception $e) { // do something } 

This is Google_Client authenticate () :

 public function authenticate($code) { $this->authenticated = true; return $this->getAuth()->authenticate($code); } 

authenticate($code) above Google_Auth_OAuth2 :: authenticate () , which at some point raises an exception:

 throw new Google_Auth_Exception( sprintf( "Error fetching OAuth2 access token, message: '%s'", $decodedResponse ), $response->getResponseHttpCode() ); 

If I put the try / catch block into Google_Client authentication, it will catch the exception, but without it the program just dies, and does not reach the main try / catch block from my application.

As far as I know, this should not happen. Any ideas?

+7
php exception-handling google-api-php-client
source share
2 answers

The problem was that the try / catch block was in a file with a name extension, and PHP requires you to use "\ Exception". Additional info: PHP namespace / exception gotcha

Example (taken from the link above):

 <?php namespace test; class Foo { public function test() { try { something_that_might_break(); } catch (\Exception $e) { // <<<<<<<<<<< You must use the backslash // something } } } ?> 
+22
source share

I'm not sure what the Google API structure looks like, and I'm not a real free PHP programmer, but you find a special type of Exception that Google Google_Auth_Exception may not inherit from.

Therefore, since your try-catch block is looking for an exception that is a member of Exception , and Google_Auth_Exception may not be a member of Exception , then your catch try block will skip it.

Try to catch a specific exception. It happened to me before in different languages.

Edit

You have sent a link to your exception from: Google / Auth / Exception Google / Auth / Exception inherits your exception: Google / Exception Google / Exception extends Exception , which in this context may be the Exception to which your class belongs.

It seems like my excuse for your try-catch block that doesn't catch exceptions is completely wrong, but wisdom can still be true. Try to catch a specific exception, then use instanceof to find out if PHP recognizes Google_Auth_Exception as a member of Exception .

+2
source share

All Articles