From 70349a72ffd9cdb70f9c1c66ea73b8bf5b217210 Mon Sep 17 00:00:00 2001 From: Matt Connew Date: Wed, 4 Dec 2024 15:46:08 -0800 Subject: [PATCH] Fix some exception handling Preserves the original stacktrace when AsyncResult is throwing stored exception Fix order of null checks so that SocketConnection actually throws stored exception when failing to connect --- .../System/ServiceModel/Channels/SocketConnection.cs | 10 +++++----- .../src/Internals/System/Runtime/AsyncResult.cs | 3 ++- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/System.ServiceModel.NetTcp/src/System/ServiceModel/Channels/SocketConnection.cs b/src/System.ServiceModel.NetTcp/src/System/ServiceModel/Channels/SocketConnection.cs index 01d00d13d70..741e05ff4b2 100644 --- a/src/System.ServiceModel.NetTcp/src/System/ServiceModel/Channels/SocketConnection.cs +++ b/src/System.ServiceModel.NetTcp/src/System/ServiceModel/Channels/SocketConnection.cs @@ -969,17 +969,17 @@ public async ValueTask ConnectAsync(Uri uri, TimeSpan timeout) } } - if (socketConnection == null) + if (lastException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( - new EndpointNotFoundException(SR.Format(SR.NoIPEndpointsFoundForHost, uri.Host))); + SocketConnectionInitiator.ConvertConnectException(lastException, uri, + timeoutHelper.ElapsedTime(), lastException)); } - if (lastException != null) + if (socketConnection == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( - SocketConnectionInitiator.ConvertConnectException(lastException, uri, - timeoutHelper.ElapsedTime(), lastException)); + new EndpointNotFoundException(SR.Format(SR.NoIPEndpointsFoundForHost, uri.Host))); } return socketConnection; diff --git a/src/System.ServiceModel.Primitives/src/Internals/System/Runtime/AsyncResult.cs b/src/System.ServiceModel.Primitives/src/Internals/System/Runtime/AsyncResult.cs index a5568c3c7aa..239d921f9d9 100644 --- a/src/System.ServiceModel.Primitives/src/Internals/System/Runtime/AsyncResult.cs +++ b/src/System.ServiceModel.Primitives/src/Internals/System/Runtime/AsyncResult.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. +using System.Runtime.ExceptionServices; using System.Threading; namespace System.Runtime @@ -348,7 +349,7 @@ protected static TAsyncResult End(IAsyncResult result) if (asyncResult._exception != null) { - throw Fx.Exception.AsError(asyncResult._exception); + ExceptionDispatchInfo.Capture(Fx.Exception.AsError(asyncResult._exception)).Throw(); } return asyncResult;