Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Can't catch exception thrown by Google API lib

I want to catch an exception that is thrown by the Google API PHP library, but for some reason it generates a 'Fatal error: uncaught exception' before reaching my catch block.

In my app I have something like this:

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

This is Google_Client's authenticate():

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

The authenticate($code) above is Google_Auth_OAuth2::authenticate(), which at some point throws the exception:

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

If I put a try/catch block in the Google_Client's authenticate, it catches the exception, but without it the program just dies instead of reaching the main try/catch block from my app.

As far as I know this shouldn't be happening. Any ideas?

like image 461
Schrute Avatar asked Mar 08 '14 01:03

Schrute


1 Answers

The problem was that the try/catch block was in a namespaced file and PHP requires you to use "\Exception". More info: PHP 5.3 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
    }
  }
}
?>
like image 193
Schrute Avatar answered Oct 02 '22 08:10

Schrute