【发布时间】:2023-03-19 17:40:02
【问题描述】:
我正在尝试从 WCF 服务向客户端应用程序抛出自定义异常。我将尽可能多地描述与此相关的代码。
例外:
using System.Runtime.Serialization;
namespace App.Exceptions
{
/// <summary>
/// General App exception
/// </summary>
[DataContract]
public class AppException : System.Exception
{
private string strMessage = "An unknown exception occurred";
/// <summary>
/// Creates a new instance of a App Exception
/// </summary>
public AppException()
{ }
/// <summary>
/// Creates a new instance of a App Exception
/// </summary>
/// <param name="Message">Message to send as exception</param>
public AppException(string Message)
{ strMessage = Message; }
public override string Message
{ get { return strMessage; } }
}
}
服务代码:
(...)
using App.Exceptions;
namespace App.Services
{
public class Service1 : IService1
{
public Service1 ()
{ }
public void TestFunction()
{
throw new AppException();
}
}
}
服务接口:
(...)
namespace App.Services.Interfaces
{
[ServiceContract]
public interface IService1
{
[OperationContract]
void TestFunction();
}
}
客户:
(...)
using App.Exceptions;
(...)
try
{
service.TestFunction();
}
catch (AppException ex)
{
}
一切正常,在服务上调用函数并抛出异常。客户端和服务器上的引用完全相同。我已经检查过了,AppException 正在同一个名称空间中被引用,所以应该没问题。
我已经尝试在服务 app.config 上设置 <serviceDebug includeExceptionDetailInFaults="True" /> 并将其设置为 False 只是为了查看我是否得到不同的异常,实际上它是不同的,所以我不太明白为什么设置断点AppException 永远不会被击中。
编辑:
服务配置:
<service name="App.Services.Service1">
<endpoint address="" binding="basicHttpBinding" contract="App.Services.Interfaces.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/App.Services/Service1/" />
</baseAddresses>
</host>
</service>
客户端配置:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8733/Design_Time_Addresses/App.Services/Service1/"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
contract="Services.IService1" name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>
【问题讨论】:
-
我也试过了。 AppException Catch 永远不会被命中。
-
您使用的是 catch (AppException ex) 还是 catch (FaultException
ex)?前者不行,后者应该。 -
我刚刚重试了,在完全按照您提到的另一个问题完成后,我在更新服务引用时遇到了问题,错误 400 元数据包含无法解决的引用。我还注意到,当调试抛出错误异常时,它显示“System.ServiceModel.FaultException`1”这是预期的行为吗?我不这么认为。
-
@rgomez 为什么不使用 Exception ex 捕获并检查?