Valentin Coudert
Valentin Coudert

Reputation: 1919

Retrieve error code and message from Google Api Client in Python

I can't find a way to retrieve the HTTP error code and the error message from a call to a Google API using the Google API Client (in Python).
I know the call can raise a HttpError (if it's not a network problem) but that's all I know.

Hope you can help

Upvotes: 1

Views: 3510

Answers (5)

One Mad Geek
One Mad Geek

Reputation: 529

You can use error_details or reason from HttpError in Google API Client(Python):

...
except HttpError as e:
    error_reason = e.reason
    error_details = e.error_details # list of dict
...

Upvotes: 0

Henrique Francisco
Henrique Francisco

Reputation: 21

I found out HttpError has a status_code property. You can find it here.

from googleapiclient.errors import HttpError
...
except HttpError as e:
    print(e.status_code)
...

Upvotes: 0

drussell
drussell

Reputation: 649

This is how to access the error details on HttpError in Google API Client(Python):

import json
...
except HttpError as e:
    error_reason = json.loads(e.content)['error']['errors'][0]['message']
...

Upvotes: 4

edvard_munch
edvard_munch

Reputation: 275

Class HttpError has a built-in _get_reason() method that calculate the reason for the error from the response content. _get_reason() source code. The method has a kind of a misleading name for me. Because I've needed to get the value of the actual reason key from a response. Not a message key that _get_reason() is getting. But the method doing exactly what is asked by Valentin.

Example of a response, decoded from bytes to JSON:

{
  "error": {
    "errors": [{
      "domain": "usageLimits",
      "reason": "dailyLimitExceeded",
      "message": "Daily Limit Exceeded. The quota will be reset at midnight Pacific Time(PT).
      You may monitor your quota usage and adjust limits in the API Console:
      https: //console.developers.google.com/apis/api/youtube.googleapis.com/quotas?project=908279247468"
    }],
    "code": 403,
    "message": "Daily Limit Exceeded. The quota will be reset at midnight Pacific Time(PT).
    You may monitor your quota usage and adjust limits in the API Console:
    https: //console.developers.google.com/apis/api/youtube.googleapis.com/quotas?project=908279247468"
  }
}

Upvotes: 0

Valentin Coudert
Valentin Coudert

Reputation: 1919

Actually, found out that e.resp.status is where the HTTP error code is stored (e being the caught exception). Still don't know how to isolate the error message.

Upvotes: 1

Related Questions