Skip to content

Commit

Permalink
Better error message for Response<T> implicit cast from null (#25580)
Browse files Browse the repository at this point in the history
  • Loading branch information
pakrym authored Nov 30, 2021
1 parent 29cd6b9 commit 35cbf80
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
13 changes: 12 additions & 1 deletion sdk/core/Azure.Core/src/ResponseOfT.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.ComponentModel;
using System.Diagnostics;

Expand Down Expand Up @@ -32,7 +33,17 @@ public abstract class Response<T>
/// Returns the value of this <see cref="Response{T}"/> object.
/// </summary>
/// <param name="response">The <see cref="Response{T}"/> instance.</param>
public static implicit operator T(Response<T> response) => response.Value;
public static implicit operator T(Response<T> response)
{
if (response == null)
{
#pragma warning disable CA1065 // Don't throw from cast operators
throw new ArgumentNullException(nameof(response), $"The implicit cast from Response<{typeof(T)}> to {typeof(T)} failed because the Response<{typeof(T)}> was null.");
#pragma warning restore CA1065
}

return response.Value;
}

/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
Expand Down
11 changes: 11 additions & 0 deletions sdk/core/Azure.Core/tests/ResponseTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ public void ValueObtainedFromCast()
Assert.AreEqual("test_name", value.Name);
}

[Test]
public void ImplicitCastFromResponseTToNullFails()
{
Response<string> response = null;
var exception = Assert.Throws<ArgumentNullException>(() =>
{
string s = response;
});
StringAssert.StartsWith("The implicit cast from Response<System.String> to System.String failed because the Response<System.String> was null.", exception.Message);
}

[Test]
public void ToStringsFormatsStatusAndValue()
{
Expand Down

0 comments on commit 35cbf80

Please sign in to comment.