|
| 1 | +# Copyright 2024 Google LLC |
| 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 | +"""AsyncIO helpers for :mod:`rest` supporting 3.7+. |
| 16 | +""" |
| 17 | + |
| 18 | + |
| 19 | +import functools |
| 20 | + |
| 21 | +import google.auth |
| 22 | +from google.api_core import exceptions |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | +class _RestCall(): |
| 27 | + """Wrapped Rest Call to map exceptions.""" |
| 28 | + |
| 29 | + def __init__(self): |
| 30 | + self._call = None |
| 31 | + |
| 32 | + def with_call(self, call): |
| 33 | + """Supplies the call object separately to keep __init__ clean.""" |
| 34 | + self._call = call |
| 35 | + return self |
| 36 | + |
| 37 | + async def __call__(self): |
| 38 | + try: |
| 39 | + return await self._call |
| 40 | + except google.auth.exceptions.TransportError as rpc_exc: |
| 41 | + raise exceptions.GoogleAPICallError(str(rpc_exc), errors=(rpc_exc,), response=rpc_exc) |
| 42 | + |
| 43 | + |
| 44 | +def wrap_errors(callable_): |
| 45 | + """Map errors for REST async callables.""" |
| 46 | + |
| 47 | + @functools.wraps(callable_) |
| 48 | + async def error_remapped_callable(*args, **kwargs): |
| 49 | + call = callable_(*args, **kwargs) |
| 50 | + call = _RestCall().with_call(call) |
| 51 | + response = await call() |
| 52 | + return response |
| 53 | + |
| 54 | + return error_remapped_callable |
0 commit comments