gpt4 book ai didi

c# - WCF/C# 无法捕获 EndpointNotFoundException

转载 作者:IT王子 更新时间:2023-10-29 04:50:31 25 4
gpt4 key购买 nike

我已经创建了一个 WCF 服务和客户端,在捕获错误之前一切正常。具体来说,我正在 try catch EndpointNotFoundException,因为无论出于何种原因服务器恰好不存在。我尝试了一个简单的 try/catch block 来捕获特定错误及其派生的通信异常,并且我尝试只捕获异常。这些都没有成功捕获异常,但是我确实得到了

A first chance exception of type 'System.ServiceModel.EndpointNotFoundException' occurred in System.ServiceModel.dll

在客户端尝试打开服务时的输出窗口中。关于我做错了什么有什么想法吗?

最佳答案

我能够复制您的问题并产生了兴趣(因为我需要同样的东西)。我什至研究了一种方法来处理\捕获第一次机会异常,但不幸的是,对于 .net Framework 3.5 及以下版本,这是不可能的(对于托管代码)。

就我而言,每当服务出现问题或访问停机服务时,我总是会收到 System.ServiceModel.CommunicationObjectFaultedException。事实证明,c# 的 using 语句是原因,因为在幕后,using 语句总是关闭服务客户端实例,即使已经遇到异常(它不会直接跳转到 catch 语句)。

发生的事情是原始异常 System.ServiceModel.EndpointNotFoundException 将被新异常 System.ServiceModel.CommunicationObjectFaultedException 每当 using 尝试关闭服务客户端实例时。

我的解决方案是不使用 using 语句,这样每当在 try block 中遇到异常时,它都会立即将异常抛给 catch block 。

尝试编写如下代码:

DashboardService.DashboardServiceClient svc = new Dashboard_WPF_Test.DashboardService.DashboardServiceClient();
try
{
svc.GetChart(0);
}
catch (System.ServiceModel.EndpointNotFoundException ex)
{
//handle endpoint not found exception here
}
catch (Exception ex)
{
//general exception handler
}
finally
{
if (!svc.State.Equals(System.ServiceModel.CommunicationState.Faulted) && svc.State.Equals(System.ServiceModel.CommunicationState.Opened))
svc.Close();
}

代替:

try
{
using (DashboardService.DashboardServiceClient svc = new Dashboard_WPF_Test.DashboardService.DashboardServiceClient())
{
svc.GetChart(0);
}
}
catch (System.ServiceModel.EndpointNotFoundException ex)
{
//handle endpoint not found exception here (I was never able to catch this type of exception using the using statement block)
}
catch (Exception ex)
{
//general exception handler
}

然后您将能够捕捉到正确的异常。

关于c# - WCF/C# 无法捕获 EndpointNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2458631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com