1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
|
# Copyright 2014 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Exceptions raised by Google API core & clients.
This module provides base classes for all errors raised by libraries based
on :mod:`google.api_core`, including both HTTP and gRPC clients.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import http.client
from typing import Optional, Dict
from typing import Union
import warnings
from google.rpc import error_details_pb2
def _warn_could_not_import_grpcio_status():
warnings.warn(
"Please install grpcio-status to obtain helpful grpc error messages.",
ImportWarning,
) # pragma: NO COVER
try:
import grpc
try:
from grpc_status import rpc_status
except ImportError: # pragma: NO COVER
_warn_could_not_import_grpcio_status()
rpc_status = None
except ImportError: # pragma: NO COVER
grpc = None
# Lookup tables for mapping exceptions from HTTP and gRPC transports.
# Populated by _GoogleAPICallErrorMeta
_HTTP_CODE_TO_EXCEPTION: Dict[int, Exception] = {}
_GRPC_CODE_TO_EXCEPTION: Dict[int, Exception] = {}
# Additional lookup table to map integer status codes to grpc status code
# grpc does not currently support initializing enums from ints
# i.e., grpc.StatusCode(5) raises an error
_INT_TO_GRPC_CODE = {}
if grpc is not None: # pragma: no branch
for x in grpc.StatusCode:
_INT_TO_GRPC_CODE[x.value[0]] = x
class GoogleAPIError(Exception):
"""Base class for all exceptions raised by Google API Clients."""
pass
class DuplicateCredentialArgs(GoogleAPIError):
"""Raised when multiple credentials are passed."""
pass
class RetryError(GoogleAPIError):
"""Raised when a function has exhausted all of its available retries.
Args:
message (str): The exception message.
cause (Exception): The last exception raised when retrying the
function.
"""
def __init__(self, message, cause):
super(RetryError, self).__init__(message)
self.message = message
self._cause = cause
@property
def cause(self):
"""The last exception raised when retrying the function."""
return self._cause
def __str__(self):
return "{}, last exception: {}".format(self.message, self.cause)
class _GoogleAPICallErrorMeta(type):
"""Metaclass for registering GoogleAPICallError subclasses."""
def __new__(mcs, name, bases, class_dict):
cls = type.__new__(mcs, name, bases, class_dict)
if cls.code is not None:
_HTTP_CODE_TO_EXCEPTION.setdefault(cls.code, cls)
if cls.grpc_status_code is not None:
_GRPC_CODE_TO_EXCEPTION.setdefault(cls.grpc_status_code, cls)
return cls
class GoogleAPICallError(GoogleAPIError, metaclass=_GoogleAPICallErrorMeta):
"""Base class for exceptions raised by calling API methods.
Args:
message (str): The exception message.
errors (Sequence[Any]): An optional list of error details.
details (Sequence[Any]): An optional list of objects defined in google.rpc.error_details.
response (Union[requests.Request, grpc.Call]): The response or
gRPC call metadata.
error_info (Union[error_details_pb2.ErrorInfo, None]): An optional object containing error info
(google.rpc.error_details.ErrorInfo).
"""
code: Union[int, None] = None
"""Optional[int]: The HTTP status code associated with this error.
This may be ``None`` if the exception does not have a direct mapping
to an HTTP error.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
"""
grpc_status_code = None
"""Optional[grpc.StatusCode]: The gRPC status code associated with this
error.
This may be ``None`` if the exception does not match up to a gRPC error.
"""
def __init__(self, message, errors=(), details=(), response=None, error_info=None):
super(GoogleAPICallError, self).__init__(message)
self.message = message
"""str: The exception message."""
self._errors = errors
self._details = details
self._response = response
self._error_info = error_info
def __str__(self):
error_msg = "{} {}".format(self.code, self.message)
if self.details:
error_msg = "{} {}".format(error_msg, self.details)
# Note: This else condition can be removed once proposal A from
# b/284179390 is implemented.
else:
if self.errors:
errors = [
f"{error.code}: {error.message}"
for error in self.errors
if hasattr(error, "code") and hasattr(error, "message")
]
if errors:
error_msg = "{} {}".format(error_msg, "\n".join(errors))
return error_msg
@property
def reason(self):
"""The reason of the error.
Reference:
https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto#L112
Returns:
Union[str, None]: An optional string containing reason of the error.
"""
return self._error_info.reason if self._error_info else None
@property
def domain(self):
"""The logical grouping to which the "reason" belongs.
Reference:
https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto#L112
Returns:
Union[str, None]: An optional string containing a logical grouping to which the "reason" belongs.
"""
return self._error_info.domain if self._error_info else None
@property
def metadata(self):
"""Additional structured details about this error.
Reference:
https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto#L112
Returns:
Union[Dict[str, str], None]: An optional object containing structured details about the error.
"""
return self._error_info.metadata if self._error_info else None
@property
def errors(self):
"""Detailed error information.
Returns:
Sequence[Any]: A list of additional error details.
"""
return list(self._errors)
@property
def details(self):
"""Information contained in google.rpc.status.details.
Reference:
https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto
https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto
Returns:
Sequence[Any]: A list of structured objects from error_details.proto
"""
return list(self._details)
@property
def response(self):
"""Optional[Union[requests.Request, grpc.Call]]: The response or
gRPC call metadata."""
return self._response
class Redirection(GoogleAPICallError):
"""Base class for for all redirection (HTTP 3xx) responses."""
class MovedPermanently(Redirection):
"""Exception mapping a ``301 Moved Permanently`` response."""
code = http.client.MOVED_PERMANENTLY
class NotModified(Redirection):
"""Exception mapping a ``304 Not Modified`` response."""
code = http.client.NOT_MODIFIED
class TemporaryRedirect(Redirection):
"""Exception mapping a ``307 Temporary Redirect`` response."""
code = http.client.TEMPORARY_REDIRECT
class ResumeIncomplete(Redirection):
"""Exception mapping a ``308 Resume Incomplete`` response.
.. note:: :attr:`http.client.PERMANENT_REDIRECT` is ``308``, but Google
APIs differ in their use of this status code.
"""
code = 308
class ClientError(GoogleAPICallError):
"""Base class for all client error (HTTP 4xx) responses."""
class BadRequest(ClientError):
"""Exception mapping a ``400 Bad Request`` response."""
code = http.client.BAD_REQUEST
class InvalidArgument(BadRequest):
"""Exception mapping a :attr:`grpc.StatusCode.INVALID_ARGUMENT` error."""
grpc_status_code = grpc.StatusCode.INVALID_ARGUMENT if grpc is not None else None
class FailedPrecondition(BadRequest):
"""Exception mapping a :attr:`grpc.StatusCode.FAILED_PRECONDITION`
error."""
grpc_status_code = grpc.StatusCode.FAILED_PRECONDITION if grpc is not None else None
class OutOfRange(BadRequest):
"""Exception mapping a :attr:`grpc.StatusCode.OUT_OF_RANGE` error."""
grpc_status_code = grpc.StatusCode.OUT_OF_RANGE if grpc is not None else None
class Unauthorized(ClientError):
"""Exception mapping a ``401 Unauthorized`` response."""
code = http.client.UNAUTHORIZED
class Unauthenticated(Unauthorized):
"""Exception mapping a :attr:`grpc.StatusCode.UNAUTHENTICATED` error."""
grpc_status_code = grpc.StatusCode.UNAUTHENTICATED if grpc is not None else None
class Forbidden(ClientError):
"""Exception mapping a ``403 Forbidden`` response."""
code = http.client.FORBIDDEN
class PermissionDenied(Forbidden):
"""Exception mapping a :attr:`grpc.StatusCode.PERMISSION_DENIED` error."""
grpc_status_code = grpc.StatusCode.PERMISSION_DENIED if grpc is not None else None
class NotFound(ClientError):
"""Exception mapping a ``404 Not Found`` response or a
:attr:`grpc.StatusCode.NOT_FOUND` error."""
code = http.client.NOT_FOUND
grpc_status_code = grpc.StatusCode.NOT_FOUND if grpc is not None else None
class MethodNotAllowed(ClientError):
"""Exception mapping a ``405 Method Not Allowed`` response."""
code = http.client.METHOD_NOT_ALLOWED
class Conflict(ClientError):
"""Exception mapping a ``409 Conflict`` response."""
code = http.client.CONFLICT
class AlreadyExists(Conflict):
"""Exception mapping a :attr:`grpc.StatusCode.ALREADY_EXISTS` error."""
grpc_status_code = grpc.StatusCode.ALREADY_EXISTS if grpc is not None else None
class Aborted(Conflict):
"""Exception mapping a :attr:`grpc.StatusCode.ABORTED` error."""
grpc_status_code = grpc.StatusCode.ABORTED if grpc is not None else None
class LengthRequired(ClientError):
"""Exception mapping a ``411 Length Required`` response."""
code = http.client.LENGTH_REQUIRED
class PreconditionFailed(ClientError):
"""Exception mapping a ``412 Precondition Failed`` response."""
code = http.client.PRECONDITION_FAILED
class RequestRangeNotSatisfiable(ClientError):
"""Exception mapping a ``416 Request Range Not Satisfiable`` response."""
code = http.client.REQUESTED_RANGE_NOT_SATISFIABLE
class TooManyRequests(ClientError):
"""Exception mapping a ``429 Too Many Requests`` response."""
code = http.client.TOO_MANY_REQUESTS
class ResourceExhausted(TooManyRequests):
"""Exception mapping a :attr:`grpc.StatusCode.RESOURCE_EXHAUSTED` error."""
grpc_status_code = grpc.StatusCode.RESOURCE_EXHAUSTED if grpc is not None else None
class Cancelled(ClientError):
"""Exception mapping a :attr:`grpc.StatusCode.CANCELLED` error."""
# This maps to HTTP status code 499. See
# https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
code = 499
grpc_status_code = grpc.StatusCode.CANCELLED if grpc is not None else None
class ServerError(GoogleAPICallError):
"""Base for 5xx responses."""
class InternalServerError(ServerError):
"""Exception mapping a ``500 Internal Server Error`` response. or a
:attr:`grpc.StatusCode.INTERNAL` error."""
code = http.client.INTERNAL_SERVER_ERROR
grpc_status_code = grpc.StatusCode.INTERNAL if grpc is not None else None
class Unknown(ServerError):
"""Exception mapping a :attr:`grpc.StatusCode.UNKNOWN` error."""
grpc_status_code = grpc.StatusCode.UNKNOWN if grpc is not None else None
class DataLoss(ServerError):
"""Exception mapping a :attr:`grpc.StatusCode.DATA_LOSS` error."""
grpc_status_code = grpc.StatusCode.DATA_LOSS if grpc is not None else None
class MethodNotImplemented(ServerError):
"""Exception mapping a ``501 Not Implemented`` response or a
:attr:`grpc.StatusCode.UNIMPLEMENTED` error."""
code = http.client.NOT_IMPLEMENTED
grpc_status_code = grpc.StatusCode.UNIMPLEMENTED if grpc is not None else None
class BadGateway(ServerError):
"""Exception mapping a ``502 Bad Gateway`` response."""
code = http.client.BAD_GATEWAY
class ServiceUnavailable(ServerError):
"""Exception mapping a ``503 Service Unavailable`` response or a
:attr:`grpc.StatusCode.UNAVAILABLE` error."""
code = http.client.SERVICE_UNAVAILABLE
grpc_status_code = grpc.StatusCode.UNAVAILABLE if grpc is not None else None
class GatewayTimeout(ServerError):
"""Exception mapping a ``504 Gateway Timeout`` response."""
code = http.client.GATEWAY_TIMEOUT
class DeadlineExceeded(GatewayTimeout):
"""Exception mapping a :attr:`grpc.StatusCode.DEADLINE_EXCEEDED` error."""
grpc_status_code = grpc.StatusCode.DEADLINE_EXCEEDED if grpc is not None else None
class AsyncRestUnsupportedParameterError(NotImplementedError):
"""Raised when an unsupported parameter is configured against async rest transport."""
pass
def exception_class_for_http_status(status_code):
"""Return the exception class for a specific HTTP status code.
Args:
status_code (int): The HTTP status code.
Returns:
:func:`type`: the appropriate subclass of :class:`GoogleAPICallError`.
"""
return _HTTP_CODE_TO_EXCEPTION.get(status_code, GoogleAPICallError)
def from_http_status(status_code, message, **kwargs):
"""Create a :class:`GoogleAPICallError` from an HTTP status code.
Args:
status_code (int): The HTTP status code.
message (str): The exception message.
kwargs: Additional arguments passed to the :class:`GoogleAPICallError`
constructor.
Returns:
GoogleAPICallError: An instance of the appropriate subclass of
:class:`GoogleAPICallError`.
"""
error_class = exception_class_for_http_status(status_code)
error = error_class(message, **kwargs)
if error.code is None:
error.code = status_code
return error
def _format_rest_error_message(error, method, url):
method = method.upper() if method else None
message = "{method} {url}: {error}".format(
method=method,
url=url,
error=error,
)
return message
# NOTE: We're moving away from `from_http_status` because it expects an aiohttp response compared
# to `format_http_response_error` which expects a more abstract response from google.auth and is
# compatible with both sync and async response types.
# TODO(https://github.com/googleapis/python-api-core/issues/691): Add type hint for response.
def format_http_response_error(
response, method: str, url: str, payload: Optional[Dict] = None
):
"""Create a :class:`GoogleAPICallError` from a google auth rest response.
Args:
response Union[google.auth.transport.Response, google.auth.aio.transport.Response]: The HTTP response.
method Optional(str): The HTTP request method.
url Optional(str): The HTTP request url.
payload Optional(dict): The HTTP response payload. If not passed in, it is read from response for a response type of google.auth.transport.Response.
Returns:
GoogleAPICallError: An instance of the appropriate subclass of
:class:`GoogleAPICallError`, with the message and errors populated
from the response.
"""
payload = {} if not payload else payload
error_message = payload.get("error", {}).get("message", "unknown error")
errors = payload.get("error", {}).get("errors", ())
# In JSON, details are already formatted in developer-friendly way.
details = payload.get("error", {}).get("details", ())
error_info_list = list(
filter(
lambda detail: detail.get("@type", "")
== "type.googleapis.com/google.rpc.ErrorInfo",
details,
)
)
error_info = error_info_list[0] if error_info_list else None
message = _format_rest_error_message(error_message, method, url)
exception = from_http_status(
response.status_code,
message,
errors=errors,
details=details,
response=response,
error_info=error_info,
)
return exception
def from_http_response(response):
"""Create a :class:`GoogleAPICallError` from a :class:`requests.Response`.
Args:
response (requests.Response): The HTTP response.
Returns:
GoogleAPICallError: An instance of the appropriate subclass of
:class:`GoogleAPICallError`, with the message and errors populated
from the response.
"""
try:
payload = response.json()
except ValueError:
payload = {"error": {"message": response.text or "unknown error"}}
return format_http_response_error(
response, response.request.method, response.request.url, payload
)
def exception_class_for_grpc_status(status_code):
"""Return the exception class for a specific :class:`grpc.StatusCode`.
Args:
status_code (grpc.StatusCode): The gRPC status code.
Returns:
:func:`type`: the appropriate subclass of :class:`GoogleAPICallError`.
"""
return _GRPC_CODE_TO_EXCEPTION.get(status_code, GoogleAPICallError)
def from_grpc_status(status_code, message, **kwargs):
"""Create a :class:`GoogleAPICallError` from a :class:`grpc.StatusCode`.
Args:
status_code (Union[grpc.StatusCode, int]): The gRPC status code.
message (str): The exception message.
kwargs: Additional arguments passed to the :class:`GoogleAPICallError`
constructor.
Returns:
GoogleAPICallError: An instance of the appropriate subclass of
:class:`GoogleAPICallError`.
"""
if isinstance(status_code, int):
status_code = _INT_TO_GRPC_CODE.get(status_code, status_code)
error_class = exception_class_for_grpc_status(status_code)
error = error_class(message, **kwargs)
if error.grpc_status_code is None:
error.grpc_status_code = status_code
return error
def _is_informative_grpc_error(rpc_exc):
return hasattr(rpc_exc, "code") and hasattr(rpc_exc, "details")
def _parse_grpc_error_details(rpc_exc):
if not rpc_status: # pragma: NO COVER
_warn_could_not_import_grpcio_status()
return [], None
try:
status = rpc_status.from_call(rpc_exc)
except NotImplementedError: # workaround
return [], None
if not status:
return [], None
possible_errors = [
error_details_pb2.BadRequest,
error_details_pb2.PreconditionFailure,
error_details_pb2.QuotaFailure,
error_details_pb2.ErrorInfo,
error_details_pb2.RetryInfo,
error_details_pb2.ResourceInfo,
error_details_pb2.RequestInfo,
error_details_pb2.DebugInfo,
error_details_pb2.Help,
error_details_pb2.LocalizedMessage,
]
error_info = None
error_details = []
for detail in status.details:
matched_detail_cls = list(
filter(lambda x: detail.Is(x.DESCRIPTOR), possible_errors)
)
# If nothing matched, use detail directly.
if len(matched_detail_cls) == 0:
info = detail
else:
info = matched_detail_cls[0]()
detail.Unpack(info)
error_details.append(info)
if isinstance(info, error_details_pb2.ErrorInfo):
error_info = info
return error_details, error_info
def from_grpc_error(rpc_exc):
"""Create a :class:`GoogleAPICallError` from a :class:`grpc.RpcError`.
Args:
rpc_exc (grpc.RpcError): The gRPC error.
Returns:
GoogleAPICallError: An instance of the appropriate subclass of
:class:`GoogleAPICallError`.
"""
# NOTE(lidiz) All gRPC error shares the parent class grpc.RpcError.
# However, check for grpc.RpcError breaks backward compatibility.
if (
grpc is not None and isinstance(rpc_exc, grpc.Call)
) or _is_informative_grpc_error(rpc_exc):
details, err_info = _parse_grpc_error_details(rpc_exc)
return from_grpc_status(
rpc_exc.code(),
rpc_exc.details(),
errors=(rpc_exc,),
details=details,
response=rpc_exc,
error_info=err_info,
)
else:
return GoogleAPICallError(str(rpc_exc), errors=(rpc_exc,), response=rpc_exc)
|