Skip to content

Commit

Permalink
CosmosClient.ReadAccountAsync: Fixes it to throw CosmosException inst…
Browse files Browse the repository at this point in the history
…ead of DocumentClientException (#2792)

I have tested the Readaccountasync method with invalid key. it is throwing document client exception instead of Cosmos Exception. So I try to catch that error in EnsureValidClientAsync method to convert it to Cosmos exception and I have added test method EnsureUnauthorized_ThrowsCosmosClientException_ReadAccountAsync in CosmosPermissionTests.cs .
  • Loading branch information
SchintaMicrosoft authored Oct 15, 2021
1 parent a8f1a3c commit 20c475d
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
20 changes: 18 additions & 2 deletions Microsoft.Azure.Cosmos/src/DocumentClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1442,6 +1442,12 @@ internal virtual async Task EnsureValidClientAsync(ITrace trace)
this.isSuccessfullyInitialized = true;
return;
}
catch (DocumentClientException ex)
{
throw Resource.CosmosExceptions.CosmosExceptionFactory.Create(
dce: ex,
trace: trace);
}
catch (Exception e)
{
DefaultTrace.TraceWarning("initializeTask failed {0}", e.ToString());
Expand All @@ -1459,8 +1465,18 @@ internal virtual async Task EnsureValidClientAsync(ITrace trace)
initTask = this.initializeTask;
}

await initTask;
this.isSuccessfullyInitialized = true;
try
{
await initTask;
this.isSuccessfullyInitialized = true;
}
catch (DocumentClientException ex)
{
throw Resource.CosmosExceptions.CosmosExceptionFactory.Create(
dce: ex,
trace: trace);
}

}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,21 @@ public async Task EnsureUnauthorized_ThrowsCosmosClientException()
Assert.AreEqual(HttpStatusCode.Unauthorized, exception.StatusCode);
}

[TestMethod]
public async Task EnsureUnauthorized_ThrowsCosmosClientException_ReadAccountAsync()
{
string authKey = ConfigurationManager.AppSettings["MasterKey"];
string endpoint = ConfigurationManager.AppSettings["GatewayEndpoint"];

// Take the key and change some middle character
authKey = authKey.Replace("m", "M");
CosmosClient cosmosClient = new CosmosClient(endpoint, authKey);

CosmosException exception1 = await Assert.ThrowsExceptionAsync<CosmosException>(() => cosmosClient.ReadAccountAsync());
Assert.AreEqual(HttpStatusCode.Unauthorized, exception1.StatusCode);

}

[TestMethod]
public async Task EnsureUnauthorized_Writes_ThrowsCosmosClientException()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -637,7 +637,7 @@ public void ValidateVersionHeader()
}
catch (AggregateException exception)
{
var dce = exception.InnerException as DocumentClientException;
var dce = exception.InnerException as CosmosException;
if (dce != null)
{
Assert.AreEqual(dce.StatusCode, HttpStatusCode.BadRequest);
Expand Down

0 comments on commit 20c475d

Please sign in to comment.