Skip to content

Commit f844230

Browse files
Replace Exception suffix with Error
PEP8 prefers that we have "Error" as the suffix for errors, which makes sense in a world where exceptions are regularly used for control flow.
1 parent 1675099 commit f844230

File tree

44 files changed

+203
-215
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+203
-215
lines changed

codegen/core/src/main/java/software/amazon/smithy/python/codegen/ClientGenerator.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,6 @@ private void generateOperationExecutor(PythonWriter writer) {
140140
writer.addStdlibImport("dataclasses", "replace");
141141

142142
writer.addDependency(SmithyPythonDependency.SMITHY_CORE);
143-
writer.addImport("smithy_core.exceptions", "SmithyRetryException");
144143
writer.addImports("smithy_core.interceptors",
145144
Set.of("Interceptor",
146145
"InterceptorChain",
@@ -259,7 +258,7 @@ private void generateOperationExecutor(PythonWriter writer) {
259258
}
260259
writer.addStdlibImport("typing", "Any");
261260
writer.addStdlibImport("asyncio", "iscoroutine");
262-
writer.addImports("smithy_core.exceptions", Set.of("SmithyException", "CallException"));
261+
writer.addImports("smithy_core.exceptions", Set.of("SmithyError", "CallError", "RetryError"));
263262
writer.pushState();
264263
writer.putContext("request", transportRequest);
265264
writer.putContext("response", transportResponse);
@@ -284,10 +283,10 @@ private void generateOperationExecutor(PythonWriter writer) {
284283
request_future, response_future,
285284
)
286285
except Exception as e:
287-
# Make sure every exception that we throw is an instance of SmithyException so
286+
# Make sure every exception that we throw is an instance of SmithyError so
288287
# customers can reliably catch everything we throw.
289-
if not isinstance(e, SmithyException):
290-
wrapped = CallException(str(e))
288+
if not isinstance(e, SmithyError):
289+
wrapped = CallError(str(e))
291290
wrapped.__cause__ = e
292291
e = wrapped
293292
@@ -385,7 +384,7 @@ private void generateOperationExecutor(PythonWriter writer) {
385384
token_to_renew=retry_token,
386385
error=output_context.response,
387386
)
388-
except SmithyRetryException:
387+
except RetryError:
389388
raise output_context.response
390389
logger.debug(
391390
"Retry needed. Attempting request #%s in %.4f seconds.",

codegen/core/src/main/java/software/amazon/smithy/python/codegen/generators/ServiceErrorGenerator.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,9 @@ public void run() {
2929
var serviceError = CodegenUtils.getServiceError(settings);
3030
writers.useFileWriter(serviceError.getDefinitionFile(), serviceError.getNamespace(), writer -> {
3131
writer.addDependency(SmithyPythonDependency.SMITHY_CORE);
32-
writer.addImport("smithy_core.exceptions", "ModeledException");
32+
writer.addImport("smithy_core.exceptions", "ModeledError");
3333
writer.write("""
34-
class $L(ModeledException):
34+
class $L(ModeledError):
3535
""\"Base error for all errors in the service.
3636
3737
Some exceptions do not extend from this class, including

codegen/core/src/main/java/software/amazon/smithy/python/codegen/generators/UnionGenerator.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ def deserialize(cls, deserializer: ShapeDeserializer) -> Self:
104104
// realistic implementation.
105105
var unknownSymbol = symbolProvider.toSymbol(shape).expectProperty(SymbolProperties.UNION_UNKNOWN);
106106
writer.pushState(new UnionMemberSection(unknownSymbol));
107-
writer.addImport("smithy_core.exceptions", "SmithyException");
107+
writer.addImport("smithy_core.exceptions", "SerializationError");
108108
writer.write("""
109109
@dataclass
110110
class $1L:
@@ -119,10 +119,10 @@ class $1L:
119119
tag: str
120120
121121
def serialize(self, serializer: ShapeSerializer):
122-
raise SmithyException("Unknown union variants may not be serialized.")
122+
raise SerializationError("Unknown union variants may not be serialized.")
123123
124124
def serialize_members(self, serializer: ShapeSerializer):
125-
raise SmithyException("Unknown union variants may not be serialized.")
125+
raise SerializationError("Unknown union variants may not be serialized.")
126126
127127
@classmethod
128128
def deserialize(cls, deserializer: ShapeDeserializer) -> Self:
@@ -147,7 +147,7 @@ private void generateDeserializer() {
147147
writer.addLogger();
148148
writer.addStdlibImports("typing", Set.of("Self", "Any"));
149149
writer.addImport("smithy_core.deserializers", "ShapeDeserializer");
150-
writer.addImport("smithy_core.exceptions", "SmithyException");
150+
writer.addImport("smithy_core.exceptions", "SerializationError");
151151

152152
// TODO: add in unknown handling
153153

@@ -164,7 +164,7 @@ def deserialize(self, deserializer: ShapeDeserializer) -> $2T:
164164
deserializer.read_struct($3T, self._consumer)
165165
166166
if self._result is None:
167-
raise SmithyException("Unions must have exactly one value, but found none.")
167+
raise SerializationError("Unions must have exactly one value, but found none.")
168168
169169
return self._result
170170
@@ -176,7 +176,7 @@ def _consumer(self, schema: Schema, de: ShapeDeserializer) -> None:
176176
177177
def _set_result(self, value: $2T) -> None:
178178
if self._result is not None:
179-
raise SmithyException("Unions must have exactly one value, but found more than one.")
179+
raise SerializationError("Unions must have exactly one value, but found more than one.")
180180
self._result = value
181181
""",
182182
deserializerSymbol.getName(),

codegen/core/src/main/java/software/amazon/smithy/python/codegen/integrations/HttpProtocolGeneratorUtils.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -139,18 +139,18 @@ public static void generateErrorDispatcher(
139139
var canReadResponseBody = canReadResponseBody(operation, context.model());
140140
delegator.useFileWriter(errorDispatcher.getDefinitionFile(), errorDispatcher.getNamespace(), writer -> {
141141
writer.pushState(new ErrorDispatcherSection(operation, errorShapeToCode, errorMessageCodeGenerator));
142-
writer.addImport("smithy_core.exceptions", "CallException");
142+
writer.addImport("smithy_core.exceptions", "CallError");
143143
// TODO: include standard retry-after in the pure-python version of this
144144
writer.write("""
145-
async def $1L(http_response: $2T, config: $3T) -> CallException:
145+
async def $1L(http_response: $2T, config: $3T) -> CallError:
146146
${4C|}
147147
148148
match code.lower():
149149
${5C|}
150150
151151
case _:
152152
is_throttle = http_response.status == 429
153-
return CallException(
153+
return CallError(
154154
message=f"{code}: {message}",
155155
fault="client" if http_response.status < 500 else "server",
156156
is_throttling_error=is_throttle,

designs/exceptions.md

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,20 @@ smithy-python clients will expose exceptions to customers.
1414

1515
## Specification
1616

17-
Every exception raised by a Smithy client MUST inherit from `SmithyException`.
17+
Every exception raised by a Smithy client MUST inherit from `SmithyError`.
1818

1919
```python
20-
class SmithyException(Exception):
20+
class SmithyError(Exception):
2121
"""Base exception type for all exceptions raised by smithy-python."""
2222
```
2323

24-
If an exception that is not a `SmithyException` is thrown while executing a
25-
request, that exception MUST be wrapped in a `SmithyException` and the
26-
`__cause__` MUST be set to the original exception.
24+
If an exception that is not a `SmithyError` is thrown while executing a request,
25+
that exception MUST be wrapped in a `SmithyError` and the `__cause__` MUST be
26+
set to the original exception.
2727

2828
Just as in normal Python programming, different exception types SHOULD be made
29-
for different kinds of exceptions. `SerializationException`, for example, will
30-
serve as the exception type for any exceptions that occur while serializing a
31-
request.
29+
for different kinds of exceptions. `SerializationError`, for example, will serve
30+
as the exception type for any exceptions that occur while serializing a request.
3231

3332
### Retryability
3433

@@ -42,7 +41,7 @@ implement.
4241
@runtime_checkable
4342
class ErrorRetryInfo(Protocol):
4443
is_retry_safe: bool | None = None
45-
"""Whether the exception is safe to retry.
44+
"""Whether the error is safe to retry.
4645
4746
A value of True does not mean a retry will occur, but rather that a retry is allowed
4847
to occur.
@@ -61,16 +60,15 @@ class ErrorRetryInfo(Protocol):
6160
"""Whether the error is a throttling error."""
6261
```
6362

64-
If an exception with `RetryInfo` is received while attempting to send a
63+
If an exception with `ErrorRetryInfo` is received while attempting to send a
6564
serialized request to the server, the contained information will be used to
6665
inform the next retry.
6766

68-
### Service Exceptions
67+
### Service Errors
6968

70-
Exceptions returned by the service MUST be a `CallException`. `CallException`s
71-
include a `fault` property that indicates whether the client or server is
72-
responsible for the exception. HTTP protocols can determine this based on the
73-
status code.
69+
Errors returned by the service MUST be a `CallError`. `CallError`s include a
70+
`fault` property that indicates whether the client or server is responsible for
71+
the exception. HTTP protocols can determine this based on the status code.
7472

7573
Similarly, protocols can and should determine retry information. HTTP protocols
7674
can generally be confident that a status code 429 is a throttling error and can
@@ -86,21 +84,21 @@ If None, then there was not enough information to determine fault.
8684

8785

8886
@dataclass(kw_only=True)
89-
class CallException(SmithyException, RetryInfo):
87+
class CallError(SmithyError, ErrorRetryInfo):
9088
fault: Fault = None
9189
message: str = field(default="", kw_only=False)
9290
```
9391

94-
#### Modeled Exceptions
92+
#### Modeled Errors
9593

9694
Most exceptions thrown by a service will be present in the Smithy model for the
9795
service. These exceptions will all be generated into the client package. Each
9896
modeled exception will be inherit from a generated exception named
99-
`ServiceException` which itself inherits from the static `ModeledException`.
97+
`ServiceError` which itself inherits from the static `ModeledError`.
10098

10199
```python
102100
@dataclass(kw_only=True)
103-
class ModeledException(CallException):
101+
class ModeledError(CallError):
104102
"""Base exception to be used for modeled errors."""
105103
```
106104

@@ -112,13 +110,13 @@ This information will be statically generated onto the exception.
112110

113111
```python
114112
@dataclass(kw_only=True)
115-
class ServiceException(ModeledException):
113+
class ServiceError(ModeledError):
116114
pass
117115

118116

119117
@dataclass(kw_only=True)
120-
class ThrottlingException(ServcieException):
121-
fault: Fault = "client"
118+
class ThrottlingError(ServiceError):
119+
fault: Fault = "server"
122120
is_retry_safe: bool | None = True
123121
is_throttling_error: bool = True
124122
```

packages/smithy-aws-core/src/smithy_aws_core/auth/sigv4.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from aws_sdk_signers import AsyncSigV4Signer, SigV4SigningProperties
77
from smithy_core.aio.interfaces.identity import IdentityResolver
8-
from smithy_core.exceptions import SmithyIdentityException
8+
from smithy_core.exceptions import SmithyIdentityError
99
from smithy_core.interfaces.identity import IdentityProperties
1010
from smithy_http.aio.interfaces.auth import HTTPAuthScheme, HTTPSigner
1111

@@ -47,7 +47,7 @@ def identity_resolver(
4747
self, *, config: SigV4Config
4848
) -> IdentityResolver[AWSCredentialsIdentity, IdentityProperties]:
4949
if not config.aws_credentials_identity_resolver:
50-
raise SmithyIdentityException(
50+
raise SmithyIdentityError(
5151
"Attempted to use SigV4 auth, but aws_credentials_identity_resolver was not "
5252
"set on the config."
5353
)

packages/smithy-aws-core/src/smithy_aws_core/credentials_resolvers/environment.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import os
44

55
from smithy_core.aio.interfaces.identity import IdentityResolver
6-
from smithy_core.exceptions import SmithyIdentityException
6+
from smithy_core.exceptions import SmithyIdentityError
77
from smithy_core.interfaces.identity import IdentityProperties
88

99
from ..identity import AWSCredentialsIdentity
@@ -29,7 +29,7 @@ async def get_identity(
2929
account_id = os.getenv("AWS_ACCOUNT_ID")
3030

3131
if access_key_id is None or secret_access_key is None:
32-
raise SmithyIdentityException(
32+
raise SmithyIdentityError(
3333
"AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required"
3434
)
3535

packages/smithy-aws-core/src/smithy_aws_core/credentials_resolvers/imds.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from smithy_core import URI
1111
from smithy_core.aio.interfaces.identity import IdentityResolver
12-
from smithy_core.exceptions import SmithyIdentityException
12+
from smithy_core.exceptions import SmithyIdentityError
1313
from smithy_core.interfaces.identity import IdentityProperties
1414
from smithy_core.interfaces.retries import RetryStrategy
1515
from smithy_core.retries import SimpleRetryStrategy
@@ -223,9 +223,7 @@ async def get_identity(
223223
expiration = datetime.fromisoformat(expiration).replace(tzinfo=UTC)
224224

225225
if access_key_id is None or secret_access_key is None:
226-
raise SmithyIdentityException(
227-
"AccessKeyId and SecretAccessKey are required"
228-
)
226+
raise SmithyIdentityError("AccessKeyId and SecretAccessKey are required")
229227

230228
self._credentials = AWSCredentialsIdentity(
231229
access_key_id=access_key_id,

packages/smithy-aws-core/tests/unit/credentials_resolvers/test_environment_credentials_resolver.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@
33

44
import pytest
55
from smithy_aws_core.credentials_resolvers import EnvironmentCredentialsResolver
6-
from smithy_core.exceptions import SmithyIdentityException
6+
from smithy_core.exceptions import SmithyIdentityError
77
from smithy_core.interfaces.identity import IdentityProperties
88

99

1010
async def test_no_values_set():
11-
with pytest.raises(SmithyIdentityException):
11+
with pytest.raises(SmithyIdentityError):
1212
await EnvironmentCredentialsResolver().get_identity(
1313
identity_properties=IdentityProperties()
1414
)
@@ -17,7 +17,7 @@ async def test_no_values_set():
1717
async def test_required_values_missing(monkeypatch: pytest.MonkeyPatch):
1818
monkeypatch.setenv("AWS_ACCOUNT_ID", "123456789012")
1919

20-
with pytest.raises(SmithyIdentityException):
20+
with pytest.raises(SmithyIdentityError):
2121
await EnvironmentCredentialsResolver().get_identity(
2222
identity_properties=IdentityProperties()
2323
)
@@ -26,7 +26,7 @@ async def test_required_values_missing(monkeypatch: pytest.MonkeyPatch):
2626
async def test_akid_missing(monkeypatch: pytest.MonkeyPatch):
2727
monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "secret")
2828

29-
with pytest.raises(SmithyIdentityException):
29+
with pytest.raises(SmithyIdentityError):
3030
await EnvironmentCredentialsResolver().get_identity(
3131
identity_properties=IdentityProperties()
3232
)
@@ -35,7 +35,7 @@ async def test_akid_missing(monkeypatch: pytest.MonkeyPatch):
3535
async def test_secret_missing(monkeypatch: pytest.MonkeyPatch):
3636
monkeypatch.setenv("AWS_ACCESS_KEY_ID", "akid")
3737

38-
with pytest.raises(SmithyIdentityException):
38+
with pytest.raises(SmithyIdentityError):
3939
await EnvironmentCredentialsResolver().get_identity(
4040
identity_properties=IdentityProperties()
4141
)

packages/smithy-aws-event-stream/src/smithy_aws_event_stream/aio/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from smithy_core.aio.interfaces.eventstream import EventPublisher, EventReceiver
1010
from smithy_core.codecs import Codec
1111
from smithy_core.deserializers import DeserializeableShape, ShapeDeserializer
12-
from smithy_core.exceptions import ExpectationNotMetException
12+
from smithy_core.exceptions import ExpectationNotMetError
1313
from smithy_core.serializers import SerializeableShape
1414

1515
from .._private.deserializers import EventDeserializer as _EventDeserializer
@@ -53,7 +53,7 @@ async def send(self, event: E) -> None:
5353
event.serialize(self._serializer)
5454
result = self._serializer.get_result()
5555
if result is None:
56-
raise ExpectationNotMetException(
56+
raise ExpectationNotMetError(
5757
"Expected an event message to be serialized, but was None."
5858
)
5959
if self._signer is not None:

0 commit comments

Comments
 (0)