Вопрос

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?

Это было полезно?

Решение

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
    }
  }
}
?>

Другие советы

I'm not sure how the structure of Google's API is, and I'm not a real fluent PHP programmer, but you're catching a specific exception type of Exception, with which Google's 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 the Google_Auth_Exception is perhaps not a member of Exception, then your try catch block will miss it.

Try catching the specific exception. This has happened to me before in many different languages.

Edit

The link you posted inherits its exception from: Google/Auth/Exception Google/Auth/Exception inherits its exception from: Google/Exception Google/Exception extends Exception, which may, in this context be the Exception that your class is referring to.

It seems my justification for your try-catch block not catching an exception is completely wrong, but the wisdom could still be true. Try catching the specific exception, then use instanceof to see if PHP recognizes Google_Auth_Exception as a member of Exception.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top