├── .github └── workflows │ └── pypi.yaml ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTORS.md ├── LICENSE ├── README.md ├── aws_error_utils ├── __init__.py ├── aws_error_utils.py └── py.typed ├── pyproject.toml └── test_aws_error_utils.py /.github/workflows/pypi.yaml: -------------------------------------------------------------------------------- 1 | name: pypi 2 | on: 3 | push: 4 | tags: "v*" 5 | jobs: 6 | test: 7 | strategy: 8 | matrix: 9 | python: ["3.7", "3.8", "3.9", "3.10"] 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions/setup-python@v2 14 | with: 15 | python-version: "${{ matrix.python }}" 16 | - run: curl -sSL https://install.python-poetry.org | python3 - 17 | shell: bash 18 | - run: poetry install 19 | shell: bash 20 | - run: poetry run pytest 21 | shell: bash 22 | - run: poetry run mypy aws_error_utils --ignore-missing-imports 23 | shell: bash 24 | build-and-publish: 25 | needs: test 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v2 29 | - uses: actions/setup-python@v2 30 | with: 31 | python-version: "3.9" 32 | - run: curl -sSL https://install.python-poetry.org | python3 - 33 | shell: bash 34 | - run: poetry build 35 | shell: bash 36 | - uses: pypa/gh-action-pypi-publish@release/v1 37 | with: 38 | user: __token__ 39 | password: ${{ secrets.PYPI_API_TOKEN }} 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | Pipfile.lock 3 | 4 | .DS_Store? 5 | ._* 6 | .Spotlight-V100 7 | .Trashes 8 | ehthumbs.db 9 | Thumbs.db 10 | *.swp 11 | 12 | *.egg-info 13 | .*project 14 | *.py[cxo] 15 | __pycache__ 16 | .venv 17 | .env 18 | 19 | .aws-sam 20 | samconfig.toml 21 | 22 | dist 23 | poetry.lock 24 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | `aws-error-utils` uses [monotonic versioning](blog.appliedcompscilab.com/monotonic_versioning_manifesto/). 4 | 5 | ## v2.7 6 | * Remove support for Python 3.6. 7 | 8 | ## v2.6 9 | * Add `errors.ALL` to match all `ClientError`s. 10 | 11 | ## v2.5 12 | * Fix type annotations. 13 | 14 | ## v2.4 15 | * Require Python 3.6 as 3.5 is EOL. 16 | * Update `AWSErrorInfo` to be a dataclass. 17 | * Add type annotations ([#4](https://github.com/benkehoe/aws-error-utils/issues/4)). 18 | * Required refactoring from plain single-file module into package for `py.typed` file; single-file module within the package is [here](https://raw.githubusercontent.com/benkehoe/aws-error-utils/stable/aws_error_utils/aws_error_utils.py). 19 | 20 | ## v1.3 21 | * Add `make_aws_error()` function for testing ([#5](https://github.com/benkehoe/aws-error-utils/issues/5)). 22 | 23 | ## v1.2 24 | * Add `errors` class for simpler syntax (README.md#errors). 25 | 26 | ## v1.1 27 | * `catch_aws_error()` adds `AWSErrorInfo` field to `ClientError`. 28 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | # aws-error-utils contributors 2 | 3 | * [Ben Kehoe](https://github.com/benkehoe) 4 | * [Ryan Scott Brown](https://github.com/ryansb) 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2020 Ben Kehoe 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws-error-utils 2 | **Making botocore.exceptions.ClientError easier to deal with** 3 | 4 | All AWS service exceptions are raised by `boto3` as a `botocore.exceptions.ClientError`, with the contents of the exception indicating what kind of exception happened. 5 | This is not very pythonic, and the contents themselves are rather opaque, most being held in dicts rather than as properties. 6 | The functions in this package help dealing with that, to make your code less verbose and require less memorization of `ClientError` contents. 7 | 8 | ## Installation 9 | 10 | [The package is on PyPI](https://pypi.org/project/aws-error-utils/) for pip-installing, but you can also just copy the [`aws_error_utils.py` file](https://raw.githubusercontent.com/benkehoe/aws-error-utils/stable/aws_error_utils/aws_error_utils.py) into your project. 11 | 12 | aws-error-utils requires Python 3.7 or higher. 13 | 14 | ## Usage 15 | If you've got code like this: 16 | 17 | ```python 18 | import boto3, botocore.exceptions 19 | 20 | s3 = boto3.client('s3') 21 | try: 22 | s3.get_object(Bucket='my-bucket', Key='example') 23 | except botocore.exceptions.ClientError as error: 24 | if error.response['Error']['Code'] == 'NoSuchBucket': 25 | print(error.response['Error']['Message']) 26 | # error handling 27 | else: 28 | raise 29 | ``` 30 | 31 | you can replace it with: 32 | 33 | ```python 34 | import boto3 35 | from aws_error_utils import errors 36 | 37 | s3 = boto3.client('s3') 38 | try: 39 | s3.get_object(Bucket='my-bucket', Key='example') 40 | except errors.NoSuchBucket as error: 41 | # or 42 | # except catch_aws_error('NoSuchBucket') as error: 43 | print(error.message) 44 | # error handling 45 | ``` 46 | 47 | If you have trouble remembering where all the contents in `ClientError` are, like these: 48 | 49 | ```python 50 | client_error.response['Error']['Code'] 51 | client_error.response['Error']['Message'] 52 | client_error.response['ResponseMetadata']['HTTPStatusCode'] 53 | client_error.operation_name 54 | ``` 55 | 56 | you can replace it with: 57 | 58 | ```python 59 | import boto3 60 | from aws_error_utils import get_aws_error_info 61 | 62 | err_info = get_aws_error_info(client_error) 63 | 64 | err_info.code 65 | err_info.message 66 | err_info.http_status_code 67 | err_info.operation_name 68 | ``` 69 | 70 | If you're using `errors` or `catch_aws_error()`, you can skip the `get_aws_error_info()` step, because the fields are set directly on the `ClientError` object: 71 | 72 | ```python 73 | import boto3 74 | from aws_error_utils import errors 75 | 76 | s3 = boto3.client('s3') 77 | try: 78 | s3.get_object(Bucket='my-bucket', Key='example') 79 | except errors.NoSuchBucket as error: 80 | error.code 81 | error.message 82 | error.http_status_code 83 | error.operation_name 84 | ``` 85 | 86 | Additionally, when you *do* need to use `ClientError`, it's imported by `aws_error_utils` so you can just use `aws_error_utils.ClientError` rather than `botocore.exceptions.ClientError` (the same is true for `BotoCoreError`, the base class of all non-`ClientError` exceptions). 87 | 88 | ## `errors` 89 | It's easiest to use the `errors` class if you don't have complex conditions to match. 90 | Using the error code as a field name in an `except` block will match that error code. 91 | Additionally, when you use this style, it sets the fields from `AWSErrorInfo` (see below) directly on the `ClientError` object. 92 | For example: 93 | 94 | ```python 95 | import boto3 96 | from aws_error_utils import errors 97 | 98 | s3 = boto3.client('s3') 99 | try: 100 | s3.get_object(Bucket='my-bucket', Key='example') 101 | except errors.NoSuchBucket as error: 102 | print(error.message) 103 | 104 | # error handling 105 | ``` 106 | 107 | You can include multiple error codes in an `except` statement, though this is slower than combining them with a single `catch_aws_error()` call. 108 | 109 | ```python 110 | import boto3 111 | from aws_error_utils import errors 112 | 113 | s3 = boto3.client('s3') 114 | try: 115 | s3.get_object(Bucket='my-bucket', Key='example') 116 | except (errors.NoSuchBucket, errors.NoSuchKey) as error: 117 | # note: catch_aws_error("NoSuchBucket", "NoSuchKey") is faster 118 | print(error.message) 119 | 120 | # error handling 121 | ``` 122 | 123 | You can catch all `ClientError`s with `errors.ALL`. 124 | 125 | You can only use this style for error codes that work as Python property names. 126 | For error codes like EC2's `InvalidInstanceID.NotFound`, you have to use `catch_aws_error()` (see below). 127 | 128 | Unfortunately, you cannot get tab completion for error codes on the `errors` class, as a comprehensive list of error codes is not available as a Python package (`botocore` has a small number, but they are few and incomplete). 129 | 130 | Note that the value of `errors.NoSuchBucket` is not an exception class representing the `NoSuchBucket` error, it is an alias for `catch_aws_error('NoSuchBucket')`. 131 | It can only be used in an `except` statement; it will raise `RuntimeError` otherwise. 132 | You also cannot instantiate the `errors` class. 133 | 134 | ## `catch_aws_error()` 135 | The function takes as input error code(s), and optionally operation name(s), to match against the current raised exception. If the exception matches, the `except` block is executed. 136 | If your error handling still needs the error object, you can still use an `as` expression, otherwise it can be omitted (just `except catch_aws_error(...):`). 137 | Additionally, `catch_aws_error()` sets the fields from `AWSErrorInfo` (see below) directly on the `ClientError` object. 138 | 139 | ```python 140 | import boto3 141 | from aws_error_utils import catch_aws_error 142 | 143 | s3 = boto3.client('s3') 144 | try: 145 | s3.get_object(Bucket='my-bucket', Key='example') 146 | except catch_aws_error('NoSuchBucket') as error: 147 | print(error.message) 148 | 149 | # error handling 150 | ``` 151 | 152 | You can provide error codes either as positional args, or as the `code` keyword argument with either as a single string or a list of strings. 153 | 154 | ```python 155 | catch_aws_error('NoSuchBucket') 156 | catch_aws_error(code='NoSuchBucket') 157 | 158 | catch_aws_error('NoSuchBucket', 'NoSuchKey') 159 | catch_aws_error(code=['NoSuchBucket', 'NoSuchKey']) 160 | ``` 161 | 162 | If there are multiple API calls in the `try` block, and you want to match against specific ones, the `operation_name` keyword argument can help. 163 | Similar to the `code` keyword argument, the operation name(s) can be provided as either as a single string or a list of strings. 164 | 165 | ```python 166 | import boto3 167 | from aws_error_utils import catch_aws_error 168 | 169 | try: 170 | s3 = boto3.client('s3') 171 | s3.list_objects_v2(Bucket='bucket-1') 172 | s3.get_object(Bucket='bucket-2', Key='example') 173 | except catch_aws_error('NoSuchBucket', operation_name='GetObject') as error: 174 | # This will be executed if the GetObject operation raises NoSuchBucket 175 | # but not if the ListObjects operation raises it 176 | ``` 177 | 178 | You must provide an error code. 179 | To match exclusively against operation name, use the `aws_error_utils.ALL_CODES` token. 180 | For completeness, there is also an `ALL_OPERATIONS` token. 181 | 182 | ```python 183 | import boto3 184 | from aws_error_utils import ALL_CODES, catch_aws_error 185 | 186 | try: 187 | s3 = boto3.client('s3') 188 | s3.list_objects_v2(Bucket='bucket-1') 189 | s3.get_object(Bucket='bucket-1', Key='example') 190 | except catch_aws_error(ALL_CODES, operation_name='ListObjectsV2') as e: 191 | # This will execute for all ClientError exceptions raised by the ListObjectsV2 call 192 | ``` 193 | 194 | For more complex conditions, instead of providing error codes and operation names, you can provide a callable to evaluate the exception. 195 | Note that unlike error codes, you can only provide a single callable. 196 | 197 | ```python 198 | import re 199 | import boto3 200 | from aws_error_utils import catch_aws_error, get_aws_error_info 201 | 202 | def matcher(e): 203 | info = get_aws_error_info(e) 204 | return re.search('does not exist', info.message) 205 | 206 | try: 207 | s3 = boto3.client('s3') 208 | s3.list_objects_v2(Bucket='bucket-1') 209 | except catch_aws_error(matcher) as e: 210 | # This will be executed if e is a ClientError and matcher(e) returns True 211 | # Note the callable can assume the exception is a ClientError 212 | ``` 213 | 214 | ## `get_aws_error_info()` 215 | This function takes a returns an `AWSErrorInfo` object, which is a [dataclass](https://docs.python.org/3/library/dataclasses.html) with the following fields: 216 | 217 | * `code` 218 | * `message` 219 | * `http_status_code` 220 | * `operation_name` 221 | * `response` (the raw response dictionary) 222 | 223 | If you're not modifying your `except` statements to use `catch_aws_error()`, this function can be useful instead of remembering exactly how this information is stored in the `ClientError` object. 224 | 225 | If you're using `catch_aws_error()`, this function isn't necessary, because it sets these fields directly on the `ClientError` object. 226 | 227 | ## `aws_error_matches()` 228 | This is the matching logic behind `catch_aws_error()`. 229 | It takes a `ClientError`, with the rest of the arguments being error codes and operation names identical to `catch_aws_error()`, except that it does not support providing a callable. 230 | 231 | ## `make_aws_error()` 232 | For testing, you can create `ClientError`s with the `make_aws_error()` function, which takes the following arguments: 233 | * `code` (required) 234 | * `message` (required) 235 | * `operation_name` (required) 236 | * `http_status_code` 237 | * `response` 238 | 239 | If a `response` dict is provided, it will be copied rather than modified. 240 | -------------------------------------------------------------------------------- /aws_error_utils/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Ben Kehoe and aws-error-utils contributors 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 | from .aws_error_utils import ( 16 | __version__, 17 | AWSErrorInfo, 18 | get_aws_error_info, 19 | ALL_CODES, 20 | ALL_OPERATIONS, 21 | aws_error_matches, 22 | catch_aws_error, 23 | BotoCoreError, 24 | ClientError, 25 | errors, 26 | make_aws_error, 27 | ) 28 | -------------------------------------------------------------------------------- /aws_error_utils/aws_error_utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Ben Kehoe and aws-error-utils contributors 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 | """ 16 | Helpful snippets: 17 | error_code = e.response.get('Error', {}).get('Code') 18 | error_msg = e.response.get('Error', {}).get('Message') 19 | status_code = e.response.get('ResponseMetadata', {}).get('HTTPStatusCode') 20 | operation_name = e.operation_name 21 | """ 22 | 23 | __version__ = "2.7.0" # update here and pyproject.toml 24 | 25 | __all__ = [ 26 | "AWSErrorInfo", 27 | "get_aws_error_info", 28 | "ALL_CODES", 29 | "ALL_OPERATIONS", 30 | "aws_error_matches", 31 | "catch_aws_error", 32 | "BotoCoreError", 33 | "ClientError", 34 | "errors", 35 | "make_aws_error", 36 | ] 37 | 38 | import dataclasses 39 | import sys 40 | from typing import Optional, List, Union, Callable, Type 41 | 42 | from botocore.exceptions import BotoCoreError, ClientError 43 | 44 | 45 | @dataclasses.dataclass 46 | class AWSErrorInfo: 47 | code: Optional[str] 48 | message: Optional[str] 49 | http_status_code: Optional[int] 50 | operation_name: str 51 | response: dict 52 | 53 | def _asdict(self) -> dict: 54 | return dataclasses.asdict(self) 55 | 56 | 57 | def get_aws_error_info(client_error: ClientError) -> AWSErrorInfo: 58 | """Returns an AWSErrorInfo namedtuple with the important details of the error extracted""" 59 | if not isinstance(client_error, ClientError): 60 | raise TypeError("Error is of type {}, not ClientError".format(client_error)) 61 | return AWSErrorInfo( 62 | code=client_error.response.get("Error", {}).get("Code"), 63 | message=client_error.response.get("Error", {}).get("Message"), 64 | http_status_code=client_error.response.get("ResponseMetadata", {}).get( 65 | "HTTPStatusCode" 66 | ), 67 | operation_name=client_error.operation_name, 68 | response=client_error.response, 69 | ) 70 | 71 | 72 | ALL_CODES = "__aws_error_utils_ALL_CODES__" 73 | ALL_OPERATIONS = "__aws_error_utils_ALL_OPERATIONS__" 74 | 75 | 76 | def _extract_tuple(arg): 77 | if arg is None: 78 | return tuple() 79 | elif isinstance(arg, str): 80 | return (arg,) 81 | else: 82 | return tuple(arg) 83 | 84 | 85 | def aws_error_matches( 86 | client_error: ClientError, 87 | *args: str, 88 | code: Union[None, str, List[str]] = None, 89 | operation_name: Union[None, str, List[str]] = None 90 | ) -> bool: 91 | """Tests if a botocore.exceptions.ClientError matches the arguments. 92 | 93 | Any positional arguments and the contents of the 'code' kwarg are matched 94 | against the Error.Code response field. 95 | If the 'operation_name' kwarg is provided, it is matched against the 96 | operation_name property. 97 | Both kwargs can either be a single string or a list of strings. 98 | The tokens aws_error_utils.ALL_CODES and aws_error_utils.ALL_OPERATIONS 99 | can be used to match all error codes and operation names. 100 | 101 | try: 102 | s3 = boto3.client('s3') 103 | s3.list_objects_v2(Bucket='bucket-1') 104 | s3.get_object(Bucket='bucket-2', Key='example') 105 | except botocore.exceptions.ClientError as e: 106 | if aws_error_matches(e, 'NoSuchBucket', operation_name='GetObject'): 107 | pass 108 | else: 109 | raise 110 | """ 111 | if not isinstance(client_error, ClientError): 112 | raise TypeError( 113 | "Error is of type {}, not ClientError".format(type(client_error)) 114 | ) 115 | err_args = args + _extract_tuple(code) 116 | op_args = _extract_tuple(operation_name) 117 | if not err_args: 118 | raise ValueError("No error codes provided") 119 | err = client_error.response.get("Error", {}).get("Code") 120 | err_matches = (err and (err in err_args)) or (ALL_CODES in err_args) 121 | op_matches = ( 122 | (client_error.operation_name in op_args) 123 | or (not op_args) 124 | or (ALL_OPERATIONS in op_args) 125 | ) 126 | return err_matches and op_matches 127 | 128 | 129 | def catch_aws_error( 130 | *args: Union[str, Callable], 131 | code: Union[None, str, List[str]] = None, 132 | operation_name: Union[None, str, List[str]] = None 133 | ) -> Type[BaseException]: 134 | """For use in an except statement, returns the current error's type if it matches the arguments, otherwise a non-matching error type 135 | 136 | Any positional arguments and the contents of the 'code' kwarg are matched 137 | against the Error.Code response field. 138 | If the 'operation_name' kwarg is provided, it is matched against the 139 | operation_name property. 140 | Both kwargs can either be a single string or a list of strings. 141 | The tokens aws_error_utils.ALL_CODES and aws_error_utils.ALL_OPERATIONS 142 | can be used to match all error codes and operation names. 143 | Alternatively, provide a callable that takes the error and returns true for a match. 144 | 145 | If the error matches, the fields from AWSErrorInfo are set on the ClientError object. 146 | 147 | try: 148 | s3 = boto3.client('s3') 149 | s3.list_objects_v2(Bucket='bucket-1') 150 | s3.get_object(Bucket='bucket-2', Key='example') 151 | except catch_aws_error('NoSuchBucket', operation_name='GetObject') as error: 152 | # error handling 153 | """ 154 | # (type, value, traceback) 155 | exc_info = sys.exc_info() 156 | if not exc_info[0]: 157 | raise RuntimeError("You must use catch_aws_error() inside an except statement") 158 | 159 | client_error = exc_info[1] 160 | matched = False 161 | if isinstance(client_error, ClientError): 162 | if len(args) == 1 and callable(args[0]): 163 | if args[0](client_error): 164 | matched = True 165 | elif aws_error_matches( 166 | client_error, *args, code=code, operation_name=operation_name # type: ignore 167 | ): 168 | matched = True 169 | if matched: 170 | err_info = get_aws_error_info(client_error) 171 | for key, value in err_info._asdict().items(): 172 | if not hasattr(client_error, key): 173 | setattr(client_error, key, value) 174 | # return the error class, which will cause a match 175 | return exc_info[0] 176 | else: 177 | # this dynamically-generated type can never match a raised exception 178 | return type("RedHerring", (BaseException,), {}) 179 | 180 | 181 | # Use a metaclass to hook into field access on the class 182 | class _ErrorsMeta(type): 183 | def __getattr__(self, name) -> Type[BaseException]: 184 | if not sys.exc_info()[0]: 185 | raise RuntimeError( 186 | "You must use {}.{} inside an except statement".format( 187 | self.__name__, name 188 | ) 189 | ) 190 | if name in ["ALL", "ALL_CODES"]: 191 | name = ALL_CODES 192 | return catch_aws_error(name) 193 | 194 | 195 | class errors(metaclass=_ErrorsMeta): 196 | """Fields on this class used in `except` blocks match ClientErrors with an error code equal to the field name. 197 | 198 | The value of the field is not a type. Instead, the field access calls catch_aws_error() with the field name. 199 | 200 | This class cannot be instantiated. 201 | 202 | try: 203 | s3 = boto3.client('s3') 204 | s3.get_object(Bucket='my-bucket', Key='example') 205 | except errors.NoSuchBucket as error: 206 | # error handling 207 | """ 208 | 209 | def __init__(self): 210 | raise RuntimeError("{} cannot be instantiated".format(self.__class__.__name__)) 211 | 212 | 213 | def make_aws_error( 214 | code: str, 215 | message: str, 216 | operation_name: str, 217 | http_status_code: Optional[int] = None, 218 | response: Optional[dict] = None, 219 | ) -> ClientError: 220 | """Create a ClientError using the given information, useful for testing. 221 | 222 | If you have an AWSErrorInfo object, you can use it with this function: 223 | make_aws_error(**my_error_info._asdict()) 224 | """ 225 | if response is None: 226 | response = {} 227 | else: 228 | response = response.copy() 229 | if code or message: 230 | response["Error"] = {} 231 | if code: 232 | response["Error"]["Code"] = code 233 | if message: 234 | response["Error"]["Message"] = message 235 | if http_status_code: 236 | if "ResponseMetadata" not in response: 237 | response["ResponseMetadata"] = {} 238 | else: 239 | response["ResponseMetadata"] = response["ResponseMetadata"].copy() 240 | response["ResponseMetadata"]["HTTPStatusCode"] = http_status_code 241 | return ClientError(response, operation_name) 242 | -------------------------------------------------------------------------------- /aws_error_utils/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benkehoe/aws-error-utils/2ac2ff3d7eddd249b4d4e935c82c03cba3c3073c/aws_error_utils/py.typed -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "aws-error-utils" 3 | version = "2.7.0" # update here and aws_error_utils.py 4 | description = "Error-handling functions for boto3/botocore" 5 | authors = ["Ben Kehoe"] 6 | license = "Apache-2.0" 7 | readme = "README.md" 8 | homepage = "https://github.com/benkehoe/aws-error-utils" 9 | repository = "https://github.com/benkehoe/aws-error-utils" 10 | classifiers = [ 11 | "Development Status :: 5 - Production/Stable", 12 | "Intended Audience :: Developers", 13 | "Intended Audience :: System Administrators", 14 | "License :: OSI Approved :: Apache Software License", 15 | "Operating System :: OS Independent", 16 | "Topic :: Utilities", 17 | ] 18 | 19 | [tool.poetry.dependencies] 20 | python = ">=3.7,<4" 21 | botocore = "*" 22 | 23 | [tool.poetry.dev-dependencies] 24 | pylint = "*" 25 | pytest = "^6.2.5" 26 | mypy = "^0.931" 27 | 28 | [build-system] 29 | requires = ["poetry_core>=1.0.0"] 30 | build-backend = "poetry.core.masonry.api" 31 | -------------------------------------------------------------------------------- /test_aws_error_utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Ben Kehoe 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 | import pytest 16 | import re 17 | import secrets 18 | 19 | from botocore.exceptions import ClientError 20 | 21 | from aws_error_utils import ( 22 | get_aws_error_info, 23 | aws_error_matches, 24 | catch_aws_error, 25 | ALL_CODES, 26 | ALL_OPERATIONS, 27 | errors, 28 | make_aws_error, 29 | ) 30 | 31 | rand_str = lambda: secrets.token_hex(4) 32 | 33 | 34 | def _make_test_error( 35 | operation_name, code=None, message=None, http_status_code=None, error=True 36 | ): 37 | response = {} 38 | if error or code or message: 39 | response["Error"] = {} 40 | if code: 41 | response["Error"]["Code"] = code 42 | if message: 43 | response["Error"]["Message"] = message 44 | if http_status_code: 45 | response["ResponseMetadata"] = {"HTTPStatusCode": http_status_code} 46 | return ClientError(response, operation_name) 47 | 48 | 49 | def test_create_error_info(): 50 | error = _make_test_error("AssumeRole", "RegionDisabled", http_status_code=403) 51 | error_info = get_aws_error_info(error) 52 | assert error_info.code == "RegionDisabled" 53 | assert error_info.operation_name == "AssumeRole" 54 | assert error_info.http_status_code == 403 55 | assert error_info.message is None 56 | 57 | not_error = ValueError("not a ClientError") 58 | with pytest.raises(TypeError): 59 | get_aws_error_info(not_error) 60 | 61 | 62 | def test_error_info_missing_code(): 63 | error = _make_test_error("AssumeRole") 64 | error_info = get_aws_error_info(error) 65 | assert error_info.code is None 66 | 67 | 68 | def test_error_matches_requries_code(): 69 | with pytest.raises(ValueError, match="No error codes provided"): 70 | error = _make_test_error("AssumeRole", "RegionDisabled") 71 | aws_error_matches(error) 72 | 73 | with pytest.raises(ValueError, match="No error codes provided"): 74 | error = _make_test_error("AssumeRole", "RegionDisabled") 75 | aws_error_matches(error, operation_name="AssumeRole") 76 | 77 | 78 | def test_error_matches_single(): 79 | error = _make_test_error("AssumeRole", "RegionDisabled") 80 | assert aws_error_matches(error, "RegionDisabled") 81 | assert aws_error_matches(error, "RegionDisabled", "OtherCode") 82 | assert aws_error_matches(error, "RegionDisabled", code="OtherCode") 83 | assert aws_error_matches(error, "RegionDisabled", code=["OtherCode"]) 84 | assert aws_error_matches(error, "OtherCode", code="RegionDisabled") 85 | assert aws_error_matches(error, "OtherCode", code=["RegionDisabled"]) 86 | 87 | assert not aws_error_matches(error, "OtherCode") 88 | assert not aws_error_matches(error, code="OtherCode") 89 | assert not aws_error_matches(error, code=["OtherCode"]) 90 | 91 | assert aws_error_matches(error, "RegionDisabled", operation_name="AssumeRole") 92 | assert aws_error_matches( 93 | error, "RegionDisabled", operation_name=["AssumeRole", "OtherOp"] 94 | ) 95 | assert not aws_error_matches(error, "RegionDisabled", operation_name="OtherOp") 96 | 97 | 98 | def test_error_matches_all(): 99 | code = rand_str() 100 | error = _make_test_error("OpName", code) 101 | 102 | assert aws_error_matches(error, ALL_CODES) 103 | assert not aws_error_matches(error, "SpecificCode") 104 | 105 | op_name = rand_str() 106 | error = _make_test_error(op_name, "SomeCode") 107 | 108 | assert aws_error_matches(error, "SomeCode", operation_name=ALL_OPERATIONS) 109 | assert not aws_error_matches(error, "SomeCode", operation_name="SpecificOperation") 110 | 111 | 112 | def test_catch(): 113 | error = _make_test_error("AssumeRole", "RegionDisabled") 114 | try: 115 | raise error 116 | except catch_aws_error("RegionDisabled") as e: 117 | assert e is error 118 | 119 | with pytest.raises(ClientError, match=re.escape(str(error))): 120 | try: 121 | raise error 122 | except catch_aws_error("OtherCode") as e: 123 | assert False 124 | 125 | def matcher(client_error): 126 | return client_error is error 127 | 128 | try: 129 | raise error 130 | except catch_aws_error(matcher) as e: 131 | assert e is error 132 | 133 | def nonmatcher(client_error): 134 | return False 135 | 136 | with pytest.raises(ClientError, match=re.escape(str(error))): 137 | try: 138 | raise error 139 | except catch_aws_error(nonmatcher) as e: 140 | assert False 141 | 142 | class OtherError(Exception): 143 | pass 144 | 145 | try: 146 | raise OtherError("test") 147 | except catch_aws_error(ALL_CODES) as e: 148 | assert False 149 | except OtherError: 150 | assert True 151 | 152 | 153 | def test_catch_sets_info(): 154 | operation_name = rand_str() 155 | code = rand_str() 156 | message = rand_str() 157 | http_status_code = 404 158 | error = _make_test_error( 159 | operation_name, code=code, message=message, http_status_code=http_status_code 160 | ) 161 | 162 | try: 163 | raise error 164 | except catch_aws_error(code) as error: 165 | assert error.operation_name == operation_name 166 | assert error.code == code 167 | assert error.message == message 168 | assert error.http_status_code == http_status_code 169 | 170 | 171 | def test_errors(): 172 | error = _make_test_error("AssumeRole", "RegionDisabled", http_status_code=403) 173 | 174 | try: 175 | raise error 176 | assert False 177 | except errors.RegionDisabled: 178 | pass 179 | 180 | try: 181 | raise error 182 | assert False 183 | except (errors.NoSuchRegion, errors.RegionDisabled): 184 | pass 185 | 186 | with pytest.raises(RuntimeError): 187 | errors.RegionDisabled 188 | 189 | with pytest.raises(RuntimeError): 190 | errors() 191 | 192 | try: 193 | raise error 194 | except errors.ALL as e: 195 | pass 196 | except Exception: 197 | assert False 198 | 199 | class OtherError(Exception): 200 | pass 201 | 202 | try: 203 | raise OtherError("test") 204 | except errors.ALL as e: 205 | assert False 206 | except OtherError: 207 | assert True 208 | 209 | def test_make_aws_error(): 210 | args = { 211 | "operation_name": "AssumeRole", 212 | "code": "RegionDisabled", 213 | "message": "Region is disabled", 214 | "http_status_code": 403, 215 | } 216 | error_standard = _make_test_error(**args) 217 | error = make_aws_error(**args) 218 | 219 | assert isinstance(error, ClientError) 220 | assert error_standard.operation_name == error.operation_name 221 | assert error_standard.response == error.response 222 | assert error_standard.args == error.args 223 | 224 | try: 225 | raise make_aws_error(**args) 226 | except errors.RegionDisabled: 227 | pass 228 | 229 | response_key1 = rand_str() 230 | response_value1 = rand_str() 231 | response_key2 = rand_str() 232 | response_key3 = rand_str() 233 | response_value3 = rand_str() 234 | response = { 235 | response_key1: response_value1, 236 | "ResponseMetadata": { 237 | response_key2: { 238 | response_key3: response_value3, 239 | } 240 | }, 241 | } 242 | 243 | error_code = rand_str() 244 | operation_name = rand_str() 245 | http_status_code = 404 246 | error = make_aws_error( 247 | code=error_code, 248 | message=None, 249 | operation_name=operation_name, 250 | http_status_code=http_status_code, 251 | response=response, 252 | ) 253 | 254 | assert not error.response is response # a copy was made 255 | assert "Error" not in response 256 | assert error.response == { 257 | "Error": {"Code": error_code}, 258 | response_key1: response_value1, 259 | "ResponseMetadata": { 260 | "HTTPStatusCode": http_status_code, 261 | response_key2: { 262 | response_key3: response_value3, 263 | }, 264 | }, 265 | } 266 | --------------------------------------------------------------------------------