diff --git a/ClientProxyBase/ClientProxyBase.cs b/ClientProxyBase/ClientProxyBase.cs index e3d4f4ad..1fc42f87 100644 --- a/ClientProxyBase/ClientProxyBase.cs +++ b/ClientProxyBase/ClientProxyBase.cs @@ -36,6 +36,40 @@ protected ClientProxyBase(HttpClient httpClient) #region Methods + protected virtual async Task HandleResponse(HttpResponseMessage responseMessage, + CancellationToken cancellationToken) + { + String result = String.Empty; + + // Read the content from the response + String content = await responseMessage.Content.ReadAsStringAsync(); + + // Check the response code + if (!responseMessage.IsSuccessStatusCode) + { + // throw a specific exception to inherited class + switch (responseMessage.StatusCode) + { + case HttpStatusCode.BadRequest: + throw new InvalidOperationException(content); + case HttpStatusCode.Unauthorized: + case HttpStatusCode.Forbidden: + throw new UnauthorizedAccessException(content); + case HttpStatusCode.NotFound: + throw new KeyNotFoundException(content); + case HttpStatusCode.InternalServerError: + throw new Exception("An internal error has occurred"); + default: + throw new Exception($"An internal error has occurred ({responseMessage.StatusCode})"); + } + } + + // Set the result + result = content; + + return result; + } + /// /// Handles the response. /// @@ -53,7 +87,7 @@ protected ClientProxyBase(HttpClient httpClient) /// An internal error has occurred /// or /// An internal error has occurred - protected virtual async Task> HandleResponse(HttpResponseMessage responseMessage, + protected virtual async Task> HandleResponseX(HttpResponseMessage responseMessage, CancellationToken cancellationToken) { String result = String.Empty; diff --git a/Shared.Tests/ClientProxyBaseTests.cs b/Shared.Tests/ClientProxyBaseTests.cs index 44eda45e..4a554b26 100644 --- a/Shared.Tests/ClientProxyBaseTests.cs +++ b/Shared.Tests/ClientProxyBaseTests.cs @@ -132,7 +132,7 @@ public TestClient(HttpClient httpClient) : base(httpClient){ } public async Task> Test(HttpResponseMessage responseMessage, CancellationToken cancellationToken){ - return await this.HandleResponse(responseMessage, cancellationToken); + return await this.HandleResponseX(responseMessage, cancellationToken); } } }