We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
HttpError error_details isn't populated unless __repr__ is called first
I was trying to handle an HttpError by looking at the contents of the `error_details` attribute. I noticed the attribute is a null-string unless I trigger the `__repr__` function first. For example, this does not work as the error_details is always `""`. I made a simple test that demonstrates the error:

```
from googleapiclient import discovery, errors

client = discovery.build(
    "discovery", "v1"
)

req = client.apis().getRest(api='fake_api', version='v1')

try:
    resp = req.execute()
except errors.HttpError as err:
    print(f'Error details are currently: "{err.error_details}"')
    print(f'Exception string representation is: "{err}"')
    print(f'Error details are currently: "{err.error_details}"')
```

The output of the above code:

```
Error details are currently: ""
Exception string representation is: "<HttpError 404 when requesting https://www.googleapis.com/discovery/v1/apis/fake_api/v1/rest?alt=json returned "Requested entity was not found.". Details: "Requested entity was not found.">"
Error details are currently: "Requested entity was not found."
```

I tested and the behavior is the same on both `google-api-python-client-1.12.8` and `google-api-python-client-2.0.2`

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `googleapiclient/errors.py`
Content:
```
1 # Copyright 2014 Google Inc. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 """Errors for the library.
16 
17 All exceptions defined by the library
18 should be defined in this file.
19 """
20 from __future__ import absolute_import
21 
22 __author__ = "jcgregorio@google.com (Joe Gregorio)"
23 
24 import json
25 
26 from googleapiclient import _helpers as util
27 
28 
29 class Error(Exception):
30     """Base error for this module."""
31 
32     pass
33 
34 
35 class HttpError(Error):
36     """HTTP data was invalid or unexpected."""
37 
38     @util.positional(3)
39     def __init__(self, resp, content, uri=None):
40         self.resp = resp
41         if not isinstance(content, bytes):
42             raise TypeError("HTTP content should be bytes")
43         self.content = content
44         self.uri = uri
45         self.error_details = ""
46 
47     def _get_reason(self):
48         """Calculate the reason for the error from the response content."""
49         reason = self.resp.reason
50         try:
51             try:
52                 data = json.loads(self.content.decode("utf-8"))
53             except json.JSONDecodeError:
54                 # In case it is not json
55                 data = self.content.decode("utf-8")
56             if isinstance(data, dict):
57                 reason = data["error"]["message"]
58                 error_detail_keyword = next((kw for kw in ["detail", "details", "message"] if kw in data["error"]), "")
59                 if error_detail_keyword:
60                     self.error_details = data["error"][error_detail_keyword]
61             elif isinstance(data, list) and len(data) > 0:
62                 first_error = data[0]
63                 reason = first_error["error"]["message"]
64                 if "details" in first_error["error"]:
65                     self.error_details = first_error["error"]["details"]
66             else:
67                 self.error_details = data
68         except (ValueError, KeyError, TypeError):
69             pass
70         if reason is None:
71             reason = ""
72         return reason
73 
74     def __repr__(self):
75         reason = self._get_reason()
76         if self.error_details:
77             return '<HttpError %s when requesting %s returned "%s". Details: "%s">' % (
78                 self.resp.status,
79                 self.uri,
80                 reason.strip(),
81                 self.error_details,
82             )
83         elif self.uri:
84             return '<HttpError %s when requesting %s returned "%s">' % (
85                 self.resp.status,
86                 self.uri,
87                 self._get_reason().strip(),
88             )
89         else:
90             return '<HttpError %s "%s">' % (self.resp.status, self._get_reason())
91 
92     __str__ = __repr__
93 
94 
95 class InvalidJsonError(Error):
96     """The JSON returned could not be parsed."""
97 
98     pass
99 
100 
101 class UnknownFileType(Error):
102     """File type unknown or unexpected."""
103 
104     pass
105 
106 
107 class UnknownLinkType(Error):
108     """Link type unknown or unexpected."""
109 
110     pass
111 
112 
113 class UnknownApiNameOrVersion(Error):
114     """No API with that name and version exists."""
115 
116     pass
117 
118 
119 class UnacceptableMimeTypeError(Error):
120     """That is an unacceptable mimetype for this operation."""
121 
122     pass
123 
124 
125 class MediaUploadSizeError(Error):
126     """Media is larger than the method can accept."""
127 
128     pass
129 
130 
131 class ResumableUploadError(HttpError):
132     """Error occurred during resumable upload."""
133 
134     pass
135 
136 
137 class InvalidChunkSizeError(Error):
138     """The given chunksize is not valid."""
139 
140     pass
141 
142 
143 class InvalidNotificationError(Error):
144     """The channel Notification is invalid."""
145 
146     pass
147 
148 
149 class BatchError(HttpError):
150     """Error occurred during batch operations."""
151 
152     @util.positional(2)
153     def __init__(self, reason, resp=None, content=None):
154         self.resp = resp
155         self.content = content
156         self.reason = reason
157 
158     def __repr__(self):
159         if getattr(self.resp, "status", None) is None:
160             return '<BatchError "%s">' % (self.reason)
161         else:
162             return '<BatchError %s "%s">' % (self.resp.status, self.reason)
163 
164     __str__ = __repr__
165 
166 
167 class UnexpectedMethodError(Error):
168     """Exception raised by RequestMockBuilder on unexpected calls."""
169 
170     @util.positional(1)
171     def __init__(self, methodId=None):
172         """Constructor for an UnexpectedMethodError."""
173         super(UnexpectedMethodError, self).__init__(
174             "Received unexpected call %s" % methodId
175         )
176 
177 
178 class UnexpectedBodyError(Error):
179     """Exception raised by RequestMockBuilder on unexpected bodies."""
180 
181     def __init__(self, expected, provided):
182         """Constructor for an UnexpectedMethodError."""
183         super(UnexpectedBodyError, self).__init__(
184             "Expected: [%s] - Provided: [%s]" % (expected, provided)
185         )
186
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/googleapiclient/errors.py b/googleapiclient/errors.py
--- a/googleapiclient/errors.py
+++ b/googleapiclient/errors.py
@@ -43,6 +43,12 @@
         self.content = content
         self.uri = uri
         self.error_details = ""
+        self._get_reason()
+
+    @property
+    def status_code(self):
+        """Return the HTTP status code from the response content."""
+        return self.resp.status
 
     def _get_reason(self):
         """Calculate the reason for the error from the response content."""

{"golden_diff": "diff --git a/googleapiclient/errors.py b/googleapiclient/errors.py\n--- a/googleapiclient/errors.py\n+++ b/googleapiclient/errors.py\n@@ -43,6 +43,12 @@\n         self.content = content\n         self.uri = uri\n         self.error_details = \"\"\n+        self._get_reason()\n+\n+    @property\n+    def status_code(self):\n+        \"\"\"Return the HTTP status code from the response content.\"\"\"\n+        return self.resp.status\n \n     def _get_reason(self):\n         \"\"\"Calculate the reason for the error from the response content.\"\"\"\n", "issue": "HttpError error_details isn't populated unless __repr__ is called first\nI was trying to handle an HttpError by looking at the contents of the `error_details` attribute. I noticed the attribute is a null-string unless I trigger the `__repr__` function first. For example, this does not work as the error_details is always `\"\"`. I made a simple test that demonstrates the error:\r\n\r\n```\r\nfrom googleapiclient import discovery, errors\r\n\r\nclient = discovery.build(\r\n    \"discovery\", \"v1\"\r\n)\r\n\r\nreq = client.apis().getRest(api='fake_api', version='v1')\r\n\r\ntry:\r\n    resp = req.execute()\r\nexcept errors.HttpError as err:\r\n    print(f'Error details are currently: \"{err.error_details}\"')\r\n    print(f'Exception string representation is: \"{err}\"')\r\n    print(f'Error details are currently: \"{err.error_details}\"')\r\n```\r\n\r\nThe output of the above code:\r\n\r\n```\r\nError details are currently: \"\"\r\nException string representation is: \"<HttpError 404 when requesting https://www.googleapis.com/discovery/v1/apis/fake_api/v1/rest?alt=json returned \"Requested entity was not found.\". Details: \"Requested entity was not found.\">\"\r\nError details are currently: \"Requested entity was not found.\"\r\n```\r\n\r\nI tested and the behavior is the same on both `google-api-python-client-1.12.8` and `google-api-python-client-2.0.2`\n", "before_files": [{"content": "# Copyright 2014 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Errors for the library.\n\nAll exceptions defined by the library\nshould be defined in this file.\n\"\"\"\nfrom __future__ import absolute_import\n\n__author__ = \"jcgregorio@google.com (Joe Gregorio)\"\n\nimport json\n\nfrom googleapiclient import _helpers as util\n\n\nclass Error(Exception):\n    \"\"\"Base error for this module.\"\"\"\n\n    pass\n\n\nclass HttpError(Error):\n    \"\"\"HTTP data was invalid or unexpected.\"\"\"\n\n    @util.positional(3)\n    def __init__(self, resp, content, uri=None):\n        self.resp = resp\n        if not isinstance(content, bytes):\n            raise TypeError(\"HTTP content should be bytes\")\n        self.content = content\n        self.uri = uri\n        self.error_details = \"\"\n\n    def _get_reason(self):\n        \"\"\"Calculate the reason for the error from the response content.\"\"\"\n        reason = self.resp.reason\n        try:\n            try:\n                data = json.loads(self.content.decode(\"utf-8\"))\n            except json.JSONDecodeError:\n                # In case it is not json\n                data = self.content.decode(\"utf-8\")\n            if isinstance(data, dict):\n                reason = data[\"error\"][\"message\"]\n                error_detail_keyword = next((kw for kw in [\"detail\", \"details\", \"message\"] if kw in data[\"error\"]), \"\")\n                if error_detail_keyword:\n                    self.error_details = data[\"error\"][error_detail_keyword]\n            elif isinstance(data, list) and len(data) > 0:\n                first_error = data[0]\n                reason = first_error[\"error\"][\"message\"]\n                if \"details\" in first_error[\"error\"]:\n                    self.error_details = first_error[\"error\"][\"details\"]\n            else:\n                self.error_details = data\n        except (ValueError, KeyError, TypeError):\n            pass\n        if reason is None:\n            reason = \"\"\n        return reason\n\n    def __repr__(self):\n        reason = self._get_reason()\n        if self.error_details:\n            return '<HttpError %s when requesting %s returned \"%s\". Details: \"%s\">' % (\n                self.resp.status,\n                self.uri,\n                reason.strip(),\n                self.error_details,\n            )\n        elif self.uri:\n            return '<HttpError %s when requesting %s returned \"%s\">' % (\n                self.resp.status,\n                self.uri,\n                self._get_reason().strip(),\n            )\n        else:\n            return '<HttpError %s \"%s\">' % (self.resp.status, self._get_reason())\n\n    __str__ = __repr__\n\n\nclass InvalidJsonError(Error):\n    \"\"\"The JSON returned could not be parsed.\"\"\"\n\n    pass\n\n\nclass UnknownFileType(Error):\n    \"\"\"File type unknown or unexpected.\"\"\"\n\n    pass\n\n\nclass UnknownLinkType(Error):\n    \"\"\"Link type unknown or unexpected.\"\"\"\n\n    pass\n\n\nclass UnknownApiNameOrVersion(Error):\n    \"\"\"No API with that name and version exists.\"\"\"\n\n    pass\n\n\nclass UnacceptableMimeTypeError(Error):\n    \"\"\"That is an unacceptable mimetype for this operation.\"\"\"\n\n    pass\n\n\nclass MediaUploadSizeError(Error):\n    \"\"\"Media is larger than the method can accept.\"\"\"\n\n    pass\n\n\nclass ResumableUploadError(HttpError):\n    \"\"\"Error occurred during resumable upload.\"\"\"\n\n    pass\n\n\nclass InvalidChunkSizeError(Error):\n    \"\"\"The given chunksize is not valid.\"\"\"\n\n    pass\n\n\nclass InvalidNotificationError(Error):\n    \"\"\"The channel Notification is invalid.\"\"\"\n\n    pass\n\n\nclass BatchError(HttpError):\n    \"\"\"Error occurred during batch operations.\"\"\"\n\n    @util.positional(2)\n    def __init__(self, reason, resp=None, content=None):\n        self.resp = resp\n        self.content = content\n        self.reason = reason\n\n    def __repr__(self):\n        if getattr(self.resp, \"status\", None) is None:\n            return '<BatchError \"%s\">' % (self.reason)\n        else:\n            return '<BatchError %s \"%s\">' % (self.resp.status, self.reason)\n\n    __str__ = __repr__\n\n\nclass UnexpectedMethodError(Error):\n    \"\"\"Exception raised by RequestMockBuilder on unexpected calls.\"\"\"\n\n    @util.positional(1)\n    def __init__(self, methodId=None):\n        \"\"\"Constructor for an UnexpectedMethodError.\"\"\"\n        super(UnexpectedMethodError, self).__init__(\n            \"Received unexpected call %s\" % methodId\n        )\n\n\nclass UnexpectedBodyError(Error):\n    \"\"\"Exception raised by RequestMockBuilder on unexpected bodies.\"\"\"\n\n    def __init__(self, expected, provided):\n        \"\"\"Constructor for an UnexpectedMethodError.\"\"\"\n        super(UnexpectedBodyError, self).__init__(\n            \"Expected: [%s] - Provided: [%s]\" % (expected, provided)\n        )\n", "path": "googleapiclient/errors.py"}], "after_files": [{"content": "# Copyright 2014 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Errors for the library.\n\nAll exceptions defined by the library\nshould be defined in this file.\n\"\"\"\nfrom __future__ import absolute_import\n\n__author__ = \"jcgregorio@google.com (Joe Gregorio)\"\n\nimport json\n\nfrom googleapiclient import _helpers as util\n\n\nclass Error(Exception):\n    \"\"\"Base error for this module.\"\"\"\n\n    pass\n\n\nclass HttpError(Error):\n    \"\"\"HTTP data was invalid or unexpected.\"\"\"\n\n    @util.positional(3)\n    def __init__(self, resp, content, uri=None):\n        self.resp = resp\n        if not isinstance(content, bytes):\n            raise TypeError(\"HTTP content should be bytes\")\n        self.content = content\n        self.uri = uri\n        self.error_details = \"\"\n        self._get_reason()\n\n    @property\n    def status_code(self):\n        \"\"\"Return the HTTP status code from the response content.\"\"\"\n        return self.resp.status\n\n    def _get_reason(self):\n        \"\"\"Calculate the reason for the error from the response content.\"\"\"\n        reason = self.resp.reason\n        try:\n            try:\n                data = json.loads(self.content.decode(\"utf-8\"))\n            except json.JSONDecodeError:\n                # In case it is not json\n                data = self.content.decode(\"utf-8\")\n            if isinstance(data, dict):\n                reason = data[\"error\"][\"message\"]\n                error_detail_keyword = next((kw for kw in [\"detail\", \"details\", \"message\"] if kw in data[\"error\"]), \"\")\n                if error_detail_keyword:\n                    self.error_details = data[\"error\"][error_detail_keyword]\n            elif isinstance(data, list) and len(data) > 0:\n                first_error = data[0]\n                reason = first_error[\"error\"][\"message\"]\n                if \"details\" in first_error[\"error\"]:\n                    self.error_details = first_error[\"error\"][\"details\"]\n            else:\n                self.error_details = data\n        except (ValueError, KeyError, TypeError):\n            pass\n        if reason is None:\n            reason = \"\"\n        return reason\n\n    def __repr__(self):\n        reason = self._get_reason()\n        if self.error_details:\n            return '<HttpError %s when requesting %s returned \"%s\". Details: \"%s\">' % (\n                self.resp.status,\n                self.uri,\n                reason.strip(),\n                self.error_details,\n            )\n        elif self.uri:\n            return '<HttpError %s when requesting %s returned \"%s\">' % (\n                self.resp.status,\n                self.uri,\n                self._get_reason().strip(),\n            )\n        else:\n            return '<HttpError %s \"%s\">' % (self.resp.status, self._get_reason())\n\n    __str__ = __repr__\n\n\nclass InvalidJsonError(Error):\n    \"\"\"The JSON returned could not be parsed.\"\"\"\n\n    pass\n\n\nclass UnknownFileType(Error):\n    \"\"\"File type unknown or unexpected.\"\"\"\n\n    pass\n\n\nclass UnknownLinkType(Error):\n    \"\"\"Link type unknown or unexpected.\"\"\"\n\n    pass\n\n\nclass UnknownApiNameOrVersion(Error):\n    \"\"\"No API with that name and version exists.\"\"\"\n\n    pass\n\n\nclass UnacceptableMimeTypeError(Error):\n    \"\"\"That is an unacceptable mimetype for this operation.\"\"\"\n\n    pass\n\n\nclass MediaUploadSizeError(Error):\n    \"\"\"Media is larger than the method can accept.\"\"\"\n\n    pass\n\n\nclass ResumableUploadError(HttpError):\n    \"\"\"Error occurred during resumable upload.\"\"\"\n\n    pass\n\n\nclass InvalidChunkSizeError(Error):\n    \"\"\"The given chunksize is not valid.\"\"\"\n\n    pass\n\n\nclass InvalidNotificationError(Error):\n    \"\"\"The channel Notification is invalid.\"\"\"\n\n    pass\n\n\nclass BatchError(HttpError):\n    \"\"\"Error occurred during batch operations.\"\"\"\n\n    @util.positional(2)\n    def __init__(self, reason, resp=None, content=None):\n        self.resp = resp\n        self.content = content\n        self.reason = reason\n\n    def __repr__(self):\n        if getattr(self.resp, \"status\", None) is None:\n            return '<BatchError \"%s\">' % (self.reason)\n        else:\n            return '<BatchError %s \"%s\">' % (self.resp.status, self.reason)\n\n    __str__ = __repr__\n\n\nclass UnexpectedMethodError(Error):\n    \"\"\"Exception raised by RequestMockBuilder on unexpected calls.\"\"\"\n\n    @util.positional(1)\n    def __init__(self, methodId=None):\n        \"\"\"Constructor for an UnexpectedMethodError.\"\"\"\n        super(UnexpectedMethodError, self).__init__(\n            \"Received unexpected call %s\" % methodId\n        )\n\n\nclass UnexpectedBodyError(Error):\n    \"\"\"Exception raised by RequestMockBuilder on unexpected bodies.\"\"\"\n\n    def __init__(self, expected, provided):\n        \"\"\"Constructor for an UnexpectedMethodError.\"\"\"\n        super(UnexpectedBodyError, self).__init__(\n            \"Expected: [%s] - Provided: [%s]\" % (expected, provided)\n        )\n", "path": "googleapiclient/errors.py"}]}