Skip to content
Open
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
217 changes: 217 additions & 0 deletions src/Sql/Sql.Test/UnitTests/ErrorResponseExceptionHelperTests.cs
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);
}
}
}
1 change: 1 addition & 0 deletions src/Sql/Sql/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
- Additional information about change #1
-->
## Upcoming Release
* Fixed error handling in Az.Sql cmdlets that inherit from `AzureSqlCmdletBase` to surface descriptive error messages instead of generic 'Operation returned an invalid status code' when API calls fail. This restores meaningful error details such as Azure Policy violation messages.

## Version 6.4.1
* Add support for the versionless AKV keys.
Expand Down
40 changes: 24 additions & 16 deletions src/Sql/Sql/Common/AzureSqlCmdletBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
using System.Management.Automation;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Sql.Models;

namespace Microsoft.Azure.Commands.Sql.Common
{
Expand Down Expand Up @@ -118,29 +119,36 @@ protected virtual string GetConfirmActionProcessMessage()
/// </summary>
public override void ExecuteCmdlet()
{
ModelAdapter = InitModelAdapter();
M model = GetEntity();
M updatedModel = ApplyUserInputToModel(model);
M responseModel = default(M);
ConfirmAction(GetConfirmActionProcessMessage(), GetResourceId(updatedModel), () =>
try
{
responseModel = PersistChanges(updatedModel);
});
ModelAdapter = InitModelAdapter();
M model = GetEntity();
M updatedModel = ApplyUserInputToModel(model);
M responseModel = default(M);
ConfirmAction(GetConfirmActionProcessMessage(), GetResourceId(updatedModel), () =>
{
responseModel = PersistChanges(updatedModel);
});

if (responseModel != null)
{
if (WriteResult())
if (responseModel != null)
{
WriteObject(TransformModelToOutputObject(responseModel), true);
if (WriteResult())
{
WriteObject(TransformModelToOutputObject(responseModel), true);
}
}
}
else
{
if (WriteResult())
else
{
WriteObject(TransformModelToOutputObject(updatedModel));
if (WriteResult())
{
WriteObject(TransformModelToOutputObject(updatedModel));
}
}
}
catch (ErrorResponseException ex)
{
throw ErrorResponseExceptionHelper.CreateFrom(ex);
}
}
}
}
104 changes: 104 additions & 0 deletions src/Sql/Sql/Common/ErrorResponseExceptionHelper.cs
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();
}
Comment thread
achyuth-ms marked this conversation as resolved.

// 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;
}
}
}
Loading