From 35cbf80e7885cc73d8c058aa41262590e439b65a Mon Sep 17 00:00:00 2001 From: Pavel Krymets Date: Tue, 30 Nov 2021 12:25:51 -0800 Subject: [PATCH] Better error message for Response implicit cast from null (#25580) --- sdk/core/Azure.Core/src/ResponseOfT.cs | 13 ++++++++++++- sdk/core/Azure.Core/tests/ResponseTests.cs | 11 +++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/sdk/core/Azure.Core/src/ResponseOfT.cs b/sdk/core/Azure.Core/src/ResponseOfT.cs index 7415dc5dc6748..b2edf877284ca 100644 --- a/sdk/core/Azure.Core/src/ResponseOfT.cs +++ b/sdk/core/Azure.Core/src/ResponseOfT.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; using System.ComponentModel; using System.Diagnostics; @@ -32,7 +33,17 @@ public abstract class Response /// Returns the value of this object. /// /// The instance. - public static implicit operator T(Response response) => response.Value; + public static implicit operator T(Response 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; + } /// [EditorBrowsable(EditorBrowsableState.Never)] diff --git a/sdk/core/Azure.Core/tests/ResponseTests.cs b/sdk/core/Azure.Core/tests/ResponseTests.cs index 4ed4373797bc9..a83ab5e633939 100644 --- a/sdk/core/Azure.Core/tests/ResponseTests.cs +++ b/sdk/core/Azure.Core/tests/ResponseTests.cs @@ -31,6 +31,17 @@ public void ValueObtainedFromCast() Assert.AreEqual("test_name", value.Name); } + [Test] + public void ImplicitCastFromResponseTToNullFails() + { + Response response = null; + var exception = Assert.Throws(() => + { + string s = response; + }); + StringAssert.StartsWith("The implicit cast from Response to System.String failed because the Response was null.", exception.Message); + } + [Test] public void ToStringsFormatsStatusAndValue() {