Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move cosmos errors.py -> exceptions.py #8226

Merged
merged 5 commits into from
Oct 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions sdk/cosmos/azure-cosmos/HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Change Log azure-cosmos

## Version 4.0.0b5

- azure.cosmos.errors module deprecated and replaced by azure.cosmos.exceptions

## Version 4.0.0b4:

- Added support for a `timeout` keyword argument to all operations to specify an absolute timeout in seconds
Expand Down
14 changes: 7 additions & 7 deletions sdk/cosmos/azure-cosmos/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export ACCOUNT_KEY=$(az cosmosdb list-keys --resource-group $RES_GROUP --name $A
Once you've populated the `ACCOUNT_URI` and `ACCOUNT_KEY` environment variables, you can create the [CosmosClient][ref_cosmosclient].

```Python
from azure.cosmos import CosmosClient, PartitionKey, errors
from azure.cosmos import CosmosClient, PartitionKey, exceptions

import os
url = os.environ['ACCOUNT_URI']
Expand Down Expand Up @@ -104,7 +104,7 @@ After authenticating your [CosmosClient][ref_cosmosclient], you can work with an
database_name = 'testDatabase'
try:
database = client.create_database(database_name)
except errors.CosmosResourceExistsError:
except exceptions.CosmosResourceExistsError:
database = client.get_database_client(database_name)
```

Expand All @@ -116,9 +116,9 @@ This example creates a container with default settings. If a container with the
container_name = 'products'
try:
container = database.create_container(id=container_name, partition_key=PartitionKey(path="/productName"))
except errors.CosmosResourceExistsError:
except exceptions.CosmosResourceExistsError:
container = database.get_container_client(container_name)
except errors.CosmosHttpResponseError:
except exceptions.CosmosHttpResponseError:
raise
```

Expand Down Expand Up @@ -230,7 +230,7 @@ For more information on TTL, see [Time to Live for Azure Cosmos DB data][cosmos_

### General

When you interact with Cosmos DB using the Python SDK, errors returned by the service correspond to the same HTTP status codes returned for REST API requests:
When you interact with Cosmos DB using the Python SDK, exceptions returned by the service correspond to the same HTTP status codes returned for REST API requests:

[HTTP Status Codes for Azure Cosmos DB][cosmos_http_status_codes]

Expand All @@ -239,7 +239,7 @@ For example, if you try to create a container using an ID (name) that's already
```Python
try:
database.create_container(id=container_name, partition_key=PartitionKey(path="/productName")
except errors.CosmosResourceExistsError:
except exceptions.CosmosResourceExistsError:
print("""Error creating container
HTTP status code 409: The ID (name) provided for the container is already in use.
The container name must be unique within the database.""")
Expand Down Expand Up @@ -279,7 +279,7 @@ For more extensive documentation on the Cosmos DB service, see the [Azure Cosmos
[ref_cosmosclient_create_database]: https://azure.github.io/azure-sdk-for-python/ref/azure.cosmos.html#azure.cosmos.CosmosClient.create_database
[ref_cosmosclient]: https://azure.github.io/azure-sdk-for-python/ref/azure.cosmos.html#azure.cosmos.CosmosClient
[ref_database]: https://azure.github.io/azure-sdk-for-python/ref/azure.cosmos.html#azure.cosmos.DatabaseProxy
[ref_httpfailure]: https://azure.github.io/azure-sdk-for-python/ref/azure.cosmos.errors.html#azure.cosmos.errors.CosmosHttpResponseError
[ref_httpfailure]: https://azure.github.io/azure-sdk-for-python/ref/azure.cosmos.exceptions.html#azure.cosmos.exceptions.CosmosHttpResponseError
[sample_database_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/cosmos/azure-cosmos/samples/DatabaseManagement
[sample_document_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/cosmos/azure-cosmos/samples/DocumentManagement
[sample_examples_misc]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/cosmos/azure-cosmos/samples/examples.py
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def needsRetry(self, error_code):
def ShouldRetry(self, exception):
"""Returns true if should retry based on the passed-in exception.

:param (errors.CosmosHttpResponseError instance) exception:
:param (exceptions.CosmosHttpResponseError instance) exception:

:rtype:
boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def __init__(self, connection_policy, global_endpoint_manager, *args):
def ShouldRetry(self, exception): # pylint: disable=unused-argument
"""Returns true if should retry based on the passed-in exception.

:param (errors.CosmosHttpResponseError instance) exception:
:param (exceptions.CosmosHttpResponseError instance) exception:

:rtype:
boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

import json
from six.moves import xrange
from azure.cosmos.errors import CosmosHttpResponseError
from azure.cosmos.exceptions import CosmosHttpResponseError
from azure.cosmos._execution_context import multi_execution_aggregator
from azure.cosmos._execution_context.base_execution_context import _QueryExecutionContextBase
from azure.cosmos._execution_context.base_execution_context import _DefaultQueryExecutionContext
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from six.moves.urllib.parse import urlparse

from . import _constants as constants
from . import errors
from . import exceptions
from ._location_cache import LocationCache

# pylint: disable=protected-access
Expand Down Expand Up @@ -126,13 +126,13 @@ def _GetDatabaseAccount(self, **kwargs):
# specified (by creating a locational endpoint) and keeping eating the exception
# until we get the database account and return None at the end, if we are not able
# to get that info from any endpoints
except errors.CosmosHttpResponseError:
except exceptions.CosmosHttpResponseError:
for location_name in self.PreferredLocations:
locational_endpoint = _GlobalEndpointManager.GetLocationalEndpoint(self.DefaultEndpoint, location_name)
try:
database_account = self._GetDatabaseAccountStub(locational_endpoint, **kwargs)
return database_account
except errors.CosmosHttpResponseError:
except exceptions.CosmosHttpResponseError:
pass

return None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__(self, max_retry_attempt_count, fixed_retry_interval_in_milliseconds
def ShouldRetry(self, exception):
"""Returns true if should retry based on the passed-in exception.

:param (errors.CosmosHttpResponseError instance) exception:
:param (exceptions.CosmosHttpResponseError instance) exception:

:rtype:
boolean
Expand Down
12 changes: 6 additions & 6 deletions sdk/cosmos/azure-cosmos/azure/cosmos/_retry_utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from azure.core.exceptions import AzureError, ClientAuthenticationError
from azure.core.pipeline.policies import RetryPolicy

from . import errors
from . import exceptions
from . import _endpoint_discovery_retry_policy
from . import _resource_throttle_retry_policy
from . import _default_retry_policy
Expand Down Expand Up @@ -85,7 +85,7 @@ def Execute(client, global_endpoint_manager, function, *args, **kwargs):
] = resourceThrottle_retry_policy.cummulative_wait_time_in_milliseconds

return result
except errors.CosmosHttpResponseError as e:
except exceptions.CosmosHttpResponseError as e:
retry_policy = None
if e.status_code == StatusCodes.FORBIDDEN and e.sub_status == SubStatusCodes.WRITE_FORBIDDEN:
retry_policy = endpointDiscovery_retry_policy
Expand Down Expand Up @@ -121,7 +121,7 @@ def Execute(client, global_endpoint_manager, function, *args, **kwargs):
if client_timeout:
kwargs['timeout'] = client_timeout - (time.time() - start_time)
if kwargs['timeout'] <= 0:
raise errors.CosmosClientTimeoutError()
raise exceptions.CosmosClientTimeoutError()


def ExecuteFunction(function, *args, **kwargs):
Expand All @@ -134,7 +134,7 @@ def _configure_timeout(request, absolute, per_request):
# type: (azure.core.pipeline.PipelineRequest, Optional[int], int) -> Optional[AzureError]
if absolute is not None:
if absolute <= 0:
raise errors.CosmosClientTimeoutError()
raise exceptions.CosmosClientTimeoutError()
if per_request:
# Both socket timeout and client timeout have been provided - use the shortest value.
request.context.options['connection_timeout'] = min(per_request, absolute)
Expand All @@ -161,7 +161,7 @@ def send(self, request):
:return: Returns the PipelineResponse or raises error if maximum retries exceeded.
:rtype: ~azure.core.pipeline.PipelineResponse
:raises ~azure.core.exceptions.AzureError: Maximum retries exceeded.
:raises ~azure.cosmos.errors.CosmosClientTimeoutError: Specified timeout exceeded.
:raises ~azure.cosmos.exceptions.CosmosClientTimeoutError: Specified timeout exceeded.
:raises ~azure.core.exceptions.ClientAuthenticationError: Authentication failed.
"""
absolute_timeout = request.context.options.pop('timeout', None)
Expand All @@ -187,7 +187,7 @@ def send(self, request):
# the authentication policy failed such that the client's request can't
# succeed--we'll never have a response to it, so propagate the exception
raise
except errors.CosmosClientTimeoutError as timeout_error:
except exceptions.CosmosClientTimeoutError as timeout_error:
timeout_error.inner_exception = retry_error
timeout_error.response = response
timeout_error.history = retry_settings['history']
Expand Down
2 changes: 1 addition & 1 deletion sdk/cosmos/azure-cosmos/azure/cosmos/_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from . import _base
from . import http_constants
from ._vector_session_token import VectorSessionToken
from .errors import CosmosHttpResponseError
from .exceptions import CosmosHttpResponseError


class SessionContainer(object):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def __init__(self, endpoint_discovery_enable, global_endpoint_manager, *args):
def ShouldRetry(self, _exception):
"""Returns true if should retry based on the passed-in exception.

:param (errors.CosmosHttpResponseError instance) exception:
:param (exceptions.CosmosHttpResponseError instance) exception:

:rtype:
boolean
Expand Down
12 changes: 6 additions & 6 deletions sdk/cosmos/azure-cosmos/azure/cosmos/_synchronized_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from azure.core.exceptions import DecodeError # type: ignore

from . import documents
from . import errors
from . import exceptions
from . import http_constants
from . import _retry_utility

Expand Down Expand Up @@ -103,7 +103,7 @@ def _Request(global_endpoint_manager, request_params, connection_policy, pipelin
if client_timeout is not None:
kwargs['timeout'] = client_timeout - (time.time() - start_time)
if kwargs['timeout'] <= 0:
raise errors.CosmosClientTimeoutError()
raise exceptions.CosmosClientTimeoutError()

if request_params.endpoint_override:
base_url = request_params.endpoint_override
Expand Down Expand Up @@ -161,13 +161,13 @@ def _Request(global_endpoint_manager, request_params, connection_policy, pipelin
data = data.decode("utf-8")

if response.status_code == 404:
raise errors.CosmosResourceNotFoundError(message=data, response=response)
raise exceptions.CosmosResourceNotFoundError(message=data, response=response)
if response.status_code == 409:
raise errors.CosmosResourceExistsError(message=data, response=response)
raise exceptions.CosmosResourceExistsError(message=data, response=response)
if response.status_code == 412:
raise errors.CosmosAccessConditionFailedError(message=data, response=response)
raise exceptions.CosmosAccessConditionFailedError(message=data, response=response)
if response.status_code >= 400:
raise errors.CosmosHttpResponseError(message=data, response=response)
raise exceptions.CosmosHttpResponseError(message=data, response=response)

result = None
if is_media:
Expand Down
6 changes: 3 additions & 3 deletions sdk/cosmos/azure-cosmos/azure/cosmos/_vector_session_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"""Session Consistency Tracking in the Azure Cosmos database service.
"""

from . import errors
from . import exceptions
from .http_constants import StatusCodes


Expand Down Expand Up @@ -120,7 +120,7 @@ def merge(self, other):
raise ValueError("Invalid Session Token (should not be None)")

if self.version == other.version and len(self.local_lsn_by_region) != len(other.local_lsn_by_region):
raise errors.CosmosHttpResponseError(
raise exceptions.CosmosHttpResponseError(
status_code=StatusCodes.INTERNAL_SERVER_ERROR,
message=("Compared session tokens '%s' and '%s' have unexpected regions."
% (self.session_token, other.session_token))
Expand All @@ -147,7 +147,7 @@ def merge(self, other):
if local_lsn2 is not None:
highest_local_lsn_by_region[region_id] = max(local_lsn1, local_lsn2)
elif self.version == other.version:
raise errors.CosmosHttpResponseError(
raise exceptions.CosmosHttpResponseError(
status_code=StatusCodes.INTERNAL_SERVER_ERROR,
message=("Compared session tokens '%s' and '%s' have unexpected regions."
% (self.session_token, other.session_token))
Expand Down
26 changes: 13 additions & 13 deletions sdk/cosmos/azure-cosmos/azure/cosmos/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

from ._cosmos_client_connection import CosmosClientConnection
from ._base import build_options
from .errors import CosmosResourceNotFoundError
from .exceptions import CosmosResourceNotFoundError
from .http_constants import StatusCodes
from .offer import Offer
from .scripts import ScriptsProxy
Expand Down Expand Up @@ -127,7 +127,7 @@ def read(
:param populate_quota_info: Enable returning collection storage quota information in response headers.
:param request_options: Dictionary of additional properties to be used for the request.
:param response_hook: a callable invoked with the response metadata
:raises ~azure.cosmos.errors.CosmosHttpResponseError: Raised if the container couldn't be retrieved.
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: Raised if the container couldn't be retrieved.
This includes if the container does not exist.
:returns: Dict representing the retrieved container.
:rtype: dict[str, Any]
Expand Down Expand Up @@ -173,7 +173,7 @@ def read_item(
:param request_options: Dictionary of additional properties to be used for the request.
:param response_hook: a callable invoked with the response metadata
:returns: Dict representing the item to be retrieved.
:raises ~azure.cosmos.errors.CosmosHttpResponseError: The given item couldn't be retrieved.
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The given item couldn't be retrieved.
:rtype: dict[str, Any]

.. admonition:: Example:
Expand Down Expand Up @@ -392,7 +392,7 @@ def replace_item(
:param request_options: Dictionary of additional properties to be used for the request.
:param response_hook: a callable invoked with the response metadata
:returns: A dict representing the item after replace went through.
:raises ~azure.cosmos.errors.CosmosHttpResponseError: The replace failed or the item with
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The replace failed or the item with
given id does not exist.
:rtype: dict[str, Any]
"""
Expand Down Expand Up @@ -438,7 +438,7 @@ def upsert_item(
:param request_options: Dictionary of additional properties to be used for the request.
:param response_hook: a callable invoked with the response metadata
:returns: A dict representing the upserted item.
:raises ~azure.cosmos.errors.CosmosHttpResponseError: The given item could not be upserted.
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The given item could not be upserted.
:rtype: dict[str, Any]
"""
request_options = build_options(kwargs)
Expand Down Expand Up @@ -483,7 +483,7 @@ def create_item(
:param request_options: Dictionary of additional properties to be used for the request.
:param response_hook: a callable invoked with the response metadata
:returns: A dict representing the new item.
:raises ~azure.cosmos.errors.CosmosHttpResponseError: Item with the given ID already exists.
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: Item with the given ID already exists.
:rtype: dict[str, Any]
"""
request_options = build_options(kwargs)
Expand Down Expand Up @@ -530,8 +530,8 @@ def delete_item(
:param post_trigger_include: trigger id to be used as post operation trigger.
:param request_options: Dictionary of additional properties to be used for the request.
:param response_hook: a callable invoked with the response metadata
:raises ~azure.cosmos.errors.CosmosHttpResponseError: The item wasn't deleted successfully.
:raises ~azure.cosmos.errors.CosmosResourceNotFoundError: The item does not exist in the container.
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The item wasn't deleted successfully.
:raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The item does not exist in the container.
:rtype: None
"""
request_options = build_options(kwargs)
Expand All @@ -558,7 +558,7 @@ def read_offer(self, **kwargs):

:param response_hook: a callable invoked with the response metadata
:returns: Offer for the container.
:raises ~azure.cosmos.errors.CosmosHttpResponseError: No offer exists for the container or
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: No offer exists for the container or
the offer could not be retrieved.
:rtype: ~azure.cosmos.Offer
"""
Expand Down Expand Up @@ -589,7 +589,7 @@ def replace_throughput(self, throughput, **kwargs):
:param throughput: The throughput to be set (an integer).
:param response_hook: a callable invoked with the response metadata
:returns: Offer for the container, updated with new throughput.
:raises ~azure.cosmos.errors.CosmosHttpResponseError: No offer exists for the container
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: No offer exists for the container
or the offer could not be updated.
:rtype: ~azure.cosmos.Offer
"""
Expand Down Expand Up @@ -694,7 +694,7 @@ def get_conflict(self, conflict, partition_key, **kwargs):
:param request_options: Dictionary of additional properties to be used for the request.
:param response_hook: a callable invoked with the response metadata
:returns: A dict representing the retrieved conflict.
:raises ~azure.cosmos.errors.CosmosHttpResponseError: The given conflict couldn't be retrieved.
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The given conflict couldn't be retrieved.
:rtype: dict[str, Any]
"""
request_options = build_options(kwargs)
Expand All @@ -719,8 +719,8 @@ def delete_conflict(self, conflict, partition_key, **kwargs):
:param partition_key: Partition key for the conflict to delete.
:param request_options: Dictionary of additional properties to be used for the request.
:param response_hook: a callable invoked with the response metadata
:raises ~azure.cosmos.errors.CosmosHttpResponseError: The conflict wasn't deleted successfully.
:raises ~azure.cosmos.errors.CosmosResourceNotFoundError: The conflict does not exist in the container.
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The conflict wasn't deleted successfully.
:raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The conflict does not exist in the container.
:rtype: None
"""
request_options = build_options(kwargs)
Expand Down
Loading