-
Notifications
You must be signed in to change notification settings - Fork 4.1k
[Sql] Fix ErrorResponseException handling to surface descriptive error messages across all Az.Sql cmdlets #29410
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
Open
achyuth-ms
wants to merge
4
commits into
Azure:main
Choose a base branch
from
achyuth-ms:exceptionloggingfix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
217 changes: 217 additions & 0 deletions
217
src/Sql/Sql.Test/UnitTests/ErrorResponseExceptionHelperTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,217 @@ | ||
| // ---------------------------------------------------------------------------------- | ||
| // | ||
| // Copyright Microsoft Corporation | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| // ---------------------------------------------------------------------------------- | ||
|
|
||
| using Microsoft.Azure.Commands.Common.Exceptions; | ||
| using Microsoft.Azure.Commands.Sql.Common; | ||
| using Microsoft.Azure.Management.Sql.Models; | ||
| using Microsoft.Azure.ServiceManagement.Common.Models; | ||
| using Microsoft.Rest; | ||
| using Microsoft.WindowsAzure.Commands.ScenarioTest; | ||
| using System.Collections.Generic; | ||
| using System.Net; | ||
| using System.Net.Http; | ||
| using Xunit; | ||
| using Xunit.Abstractions; | ||
|
|
||
| namespace Microsoft.Azure.Commands.Sql.Test.UnitTests | ||
| { | ||
| public class ErrorResponseExceptionHelperTests | ||
| { | ||
| public ErrorResponseExceptionHelperTests(ITestOutputHelper output) | ||
| { | ||
| XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output)); | ||
| } | ||
|
|
||
| [Fact] | ||
| [Trait(Category.AcceptanceType, Category.CheckIn)] | ||
| public void CreateFrom_WithBodyErrorMessage_ReturnsDetailedMessage() | ||
| { | ||
| // Arrange | ||
| var ex = new ErrorResponseException("Operation returned an invalid status code 'Forbidden'") | ||
| { | ||
| Body = new ErrorResponse(new ErrorDetail( | ||
| code: "RequestDisallowedByPolicy", | ||
| message: "Resource 'myserver' was disallowed by policy.")) | ||
| }; | ||
|
|
||
| // Act | ||
| var result = ErrorResponseExceptionHelper.CreateFrom(ex); | ||
|
|
||
| // Assert | ||
| Assert.IsType<AzPSCloudException>(result); | ||
| Assert.Contains("Resource 'myserver' was disallowed by policy.", result.Message); | ||
| } | ||
|
|
||
| [Fact] | ||
| [Trait(Category.AcceptanceType, Category.CheckIn)] | ||
| public void CreateFrom_WithBodyErrorDetails_IncludesDetailMessages() | ||
| { | ||
| // Arrange | ||
| var details = new List<ErrorDetail> | ||
| { | ||
| new ErrorDetail(code: "PolicyViolation", message: "TLS version must be 1.2 or higher."), | ||
| new ErrorDetail(code: "PolicyViolation", message: "Public network access must be disabled.") | ||
| }; | ||
| var ex = new ErrorResponseException("Operation returned an invalid status code 'Forbidden'") | ||
| { | ||
| Body = new ErrorResponse(new ErrorDetail( | ||
| code: "RequestDisallowedByPolicy", | ||
| message: "Resource was disallowed by policy.", | ||
| details: details)) | ||
| }; | ||
|
|
||
| // Act | ||
| var result = ErrorResponseExceptionHelper.CreateFrom(ex); | ||
|
|
||
| // Assert | ||
| Assert.IsType<AzPSCloudException>(result); | ||
| Assert.Contains("Resource was disallowed by policy.", result.Message); | ||
| Assert.Contains("TLS version must be 1.2 or higher.", result.Message); | ||
| Assert.Contains("Public network access must be disabled.", result.Message); | ||
| } | ||
|
|
||
| [Fact] | ||
| [Trait(Category.AcceptanceType, Category.CheckIn)] | ||
| public void CreateFrom_WithResponseContentArmFormat_ParsesErrorMessage() | ||
| { | ||
| // Arrange — Body is null, but Response.Content has the ARM error JSON | ||
| var httpResponse = new HttpResponseMessage(HttpStatusCode.NotFound) | ||
| { | ||
| Content = new StringContent("{\"error\":{\"code\":\"ResourceNotFound\",\"message\":\"The Resource 'Microsoft.Sql/servers/myserver' was not found.\"}}") | ||
| }; | ||
| var ex = new ErrorResponseException("Operation returned an invalid status code 'NotFound'") | ||
| { | ||
| Response = new HttpResponseMessageWrapper(httpResponse, "{\"error\":{\"code\":\"ResourceNotFound\",\"message\":\"The Resource 'Microsoft.Sql/servers/myserver' was not found.\"}}") | ||
| }; | ||
|
|
||
| // Act | ||
| var result = ErrorResponseExceptionHelper.CreateFrom(ex); | ||
|
|
||
| // Assert | ||
| Assert.IsType<AzPSCloudException>(result); | ||
| Assert.Contains("The Resource 'Microsoft.Sql/servers/myserver' was not found.", result.Message); | ||
| } | ||
|
|
||
| [Fact] | ||
| [Trait(Category.AcceptanceType, Category.CheckIn)] | ||
| public void CreateFrom_WithResponseContentFlatFormat_ParsesMessage() | ||
| { | ||
| // Arrange — Body is null, Response.Content has flat "Message" key | ||
| var httpResponse = new HttpResponseMessage(HttpStatusCode.BadRequest) | ||
| { | ||
| Content = new StringContent("{\"Message\":\"Only one active directory allowed.\"}") | ||
| }; | ||
| var ex = new ErrorResponseException("Operation returned an invalid status code 'BadRequest'") | ||
| { | ||
| Response = new HttpResponseMessageWrapper(httpResponse, "{\"Message\":\"Only one active directory allowed.\"}") | ||
| }; | ||
|
|
||
| // Act | ||
| var result = ErrorResponseExceptionHelper.CreateFrom(ex); | ||
|
|
||
| // Assert | ||
| Assert.IsType<AzPSCloudException>(result); | ||
| Assert.Contains("Only one active directory allowed.", result.Message); | ||
| } | ||
|
|
||
| [Fact] | ||
| [Trait(Category.AcceptanceType, Category.CheckIn)] | ||
| public void CreateFrom_WithNoBodyAndNoContent_ReturnsOriginalMessage() | ||
| { | ||
| // Arrange — No body, no response content | ||
| var ex = new ErrorResponseException("Operation returned an invalid status code 'InternalServerError'"); | ||
|
|
||
| // Act | ||
| var result = ErrorResponseExceptionHelper.CreateFrom(ex); | ||
|
|
||
| // Assert | ||
| Assert.IsType<AzPSCloudException>(result); | ||
| Assert.Equal("Operation returned an invalid status code 'InternalServerError'", result.Message); | ||
| } | ||
|
|
||
| [Fact] | ||
| [Trait(Category.AcceptanceType, Category.CheckIn)] | ||
| public void CreateFrom_WithInvalidJsonContent_ReturnsOriginalMessage() | ||
| { | ||
| // Arrange — Response content is not valid JSON | ||
| var httpResponse = new HttpResponseMessage(HttpStatusCode.BadRequest) | ||
| { | ||
| Content = new StringContent("This is not JSON") | ||
| }; | ||
| var ex = new ErrorResponseException("Operation returned an invalid status code 'BadRequest'") | ||
| { | ||
| Response = new HttpResponseMessageWrapper(httpResponse, "This is not JSON") | ||
| }; | ||
|
|
||
| // Act | ||
| var result = ErrorResponseExceptionHelper.CreateFrom(ex); | ||
|
|
||
| // Assert | ||
| Assert.IsType<AzPSCloudException>(result); | ||
| Assert.Equal("Operation returned an invalid status code 'BadRequest'", result.Message); | ||
| } | ||
|
|
||
| [Fact] | ||
| [Trait(Category.AcceptanceType, Category.CheckIn)] | ||
| public void CreateFrom_BodyTakesPrecedenceOverResponseContent() | ||
| { | ||
| // Arrange — Both Body and Response.Content have error info; Body should win | ||
| var httpResponse = new HttpResponseMessage(HttpStatusCode.Forbidden) | ||
| { | ||
| Content = new StringContent("{\"error\":{\"code\":\"Forbidden\",\"message\":\"Response content message\"}}") | ||
| }; | ||
| var ex = new ErrorResponseException("Operation returned an invalid status code 'Forbidden'") | ||
| { | ||
| Body = new ErrorResponse(new ErrorDetail( | ||
| code: "RequestDisallowedByPolicy", | ||
| message: "Body error message")), | ||
| Response = new HttpResponseMessageWrapper(httpResponse, "{\"error\":{\"code\":\"Forbidden\",\"message\":\"Response content message\"}}") | ||
| }; | ||
|
|
||
| // Act | ||
| var result = ErrorResponseExceptionHelper.CreateFrom(ex); | ||
|
|
||
| // Assert | ||
| Assert.Contains("Body error message", result.Message); | ||
| Assert.DoesNotContain("Response content message", result.Message); | ||
| } | ||
|
|
||
| [Fact] | ||
| [Trait(Category.AcceptanceType, Category.CheckIn)] | ||
| public void CreateFrom_PreservesInnerExceptionAndContext() | ||
| { | ||
| // Arrange | ||
| var httpResponse = new HttpResponseMessage(HttpStatusCode.Forbidden); | ||
| var ex = new ErrorResponseException("Operation returned an invalid status code 'Forbidden'") | ||
| { | ||
| Body = new ErrorResponse(new ErrorDetail( | ||
| code: "AuthorizationFailed", | ||
| message: "Authorization failed.")), | ||
| Request = new HttpRequestMessageWrapper(new HttpRequestMessage(HttpMethod.Get, "https://management.azure.com/test"), ""), | ||
| Response = new HttpResponseMessageWrapper(httpResponse, "") | ||
| }; | ||
|
|
||
| // Act | ||
| var result = ErrorResponseExceptionHelper.CreateFrom(ex); | ||
|
|
||
| // Assert — inner exception is preserved | ||
| Assert.IsType<ErrorResponseException>(result.InnerException); | ||
| // Assert — ErrorCode is propagated | ||
| Assert.True(result.Data.Contains("CloudErrorCode")); | ||
| // Assert — Request and Response are set | ||
| Assert.NotNull(result.Request); | ||
| Assert.NotNull(result.Response); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| // ---------------------------------------------------------------------------------- | ||
| // | ||
| // Copyright Microsoft Corporation | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| // ---------------------------------------------------------------------------------- | ||
|
|
||
| using Microsoft.Azure.Commands.Common.Exceptions; | ||
| using Microsoft.Azure.Management.Sql.Models; | ||
| using Newtonsoft.Json.Linq; | ||
| using System; | ||
| using System.Linq; | ||
| using System.Text; | ||
|
|
||
| namespace Microsoft.Azure.Commands.Sql.Common | ||
| { | ||
| /// <summary> | ||
| /// Helper class to convert ErrorResponseException to AzPSCloudException with descriptive error messages. | ||
| /// Due to a change in the SDK generator when common-types v5 ErrorResponse schema is used, | ||
| /// the ErrorResponseException.Message is not populated with the actual error details. | ||
| /// This helper extracts the real error message from the response body. | ||
| /// </summary> | ||
| internal static class ErrorResponseExceptionHelper | ||
| { | ||
| /// <summary> | ||
| /// Creates an AzPSCloudException from an ErrorResponseException by extracting | ||
| /// the actual error message from the response body. | ||
| /// </summary> | ||
| /// <param name="ex">The original ErrorResponseException</param> | ||
| /// <returns>An AzPSCloudException with the descriptive error message</returns> | ||
| internal static AzPSCloudException CreateFrom(ErrorResponseException ex) | ||
| { | ||
| // First try to get the message from the structured Body object | ||
| string detailedMessage = ex.Body?.Error?.Message; | ||
|
|
||
| // Append error details if available (e.g., Azure Policy violation details) | ||
| if (!string.IsNullOrEmpty(detailedMessage) && ex.Body?.Error?.Details != null && ex.Body.Error.Details.Any()) | ||
| { | ||
| var sb = new StringBuilder(detailedMessage); | ||
| foreach (var detail in ex.Body.Error.Details) | ||
| { | ||
| if (!string.IsNullOrEmpty(detail.Message)) | ||
| { | ||
| sb.AppendLine(); | ||
| sb.Append(detail.Message); | ||
| } | ||
| } | ||
| detailedMessage = sb.ToString(); | ||
| } | ||
|
|
||
| // If that didn't work, try parsing the raw response content | ||
| if (string.IsNullOrEmpty(detailedMessage) && ex.Response != null && !string.IsNullOrEmpty(ex.Response.Content)) | ||
| { | ||
| try | ||
| { | ||
| var parsed = JObject.Parse(ex.Response.Content); | ||
|
|
||
| var errorObj = parsed["error"] as JObject; | ||
| if (errorObj != null) | ||
| { | ||
| JToken errorMessage; | ||
| if (errorObj.TryGetValue("message", StringComparison.OrdinalIgnoreCase, out errorMessage)) | ||
| { | ||
| detailedMessage = errorMessage.ToString(); | ||
| } | ||
| } | ||
| else | ||
| { | ||
| var messageToken = parsed["Message"]; | ||
| if (messageToken != null) | ||
| { | ||
| detailedMessage = messageToken.ToString(); | ||
| } | ||
| } | ||
| } | ||
| catch (Exception) | ||
| { | ||
| // JSON parsing or property access failed — fall through to use original message | ||
| } | ||
| } | ||
|
|
||
| var message = !string.IsNullOrEmpty(detailedMessage) ? detailedMessage : ex.Message; | ||
| var wrappedException = new AzPSCloudException(message, message, ex) | ||
| { | ||
| Request = ex.Request, | ||
| Response = ex.Response, | ||
| }; | ||
|
|
||
| if (!string.IsNullOrEmpty(ex.Body?.Error?.Code)) | ||
| { | ||
| wrappedException.Data["CloudErrorCode"] = ex.Body.Error.Code; | ||
| } | ||
|
|
||
| return wrappedException; | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.