问题描述
public class InvalidCodeException:Exception
{
public InvalidCodeException()
{
}
public InvalidCodeException(string message)
:base(message)
{
}
public InvalidCodeException(string message,Exception innerException)
:base(message,innerException)
{
}
}
$ c $项目B中的一个WCF服务的
项目C中的客户端
项目B中引用了项目A, C。
我正在从项目B中抛出InvalidCodeException并捕获在Project C中。
问题是当调试时,异常没有捕获在
catch(InvalidCodeException ex)
{
Trace.WriteLine(CustomException);
throw;
}
但在
catch(Exception ex)
{throw;
解决方案
WCF不会自动序列化异常,因为很多原因(例如,客户端可能用其他语言编写而不是C#,并且在与.NET不同的平台上运行)。
然而,WCF将序列化一些异常信息进入FaultException对象。例如,这个基本信息包含异常类名称。如果使用通用的FaultException类型,则可以在其中存储一些其他数据。
I.e FaultException< FaultInfo>
其中 FaultInfo
是存储其他异常数据的类。不要忘记在数据类属性中添加数据契约序列化属性。
此外,您应该将FaultContract属性应用于应该抛出类型的FaultExceptions的方法。 p>
[OperationContract]
[FaultContract(typeof(FaultInfo))]
void DoSomething();
I have a Custom class, InvalidCodeException in Project A
public class InvalidCodeException : Exception
{
public InvalidCodeException ()
{
}
public InvalidCodeException (string message)
: base(message)
{
}
public InvalidCodeException (string message, Exception innerException)
: base(message, innerException)
{
}
}
a WCF service in Project B.And a client in Project C.Project A is referenced in Project B and C.
I am throwing InvalidCodeException from Project B and catching in Project C.Problem is that when debuggin, the exception is not catching in
catch (InvalidCodeException ex)
{
Trace.WriteLine("CustomException");
throw;
}
but in
catch (Exception ex)
{ throw; }
解决方案 WCF will not serialize exceptions automatically, for many reasons(e.g. client may be written in some other language than C#, and run on platform that is different from .NET).
However, WCF will serialize some exception information into FaultException objects. This basic information contains exception class name, for example. You may store some additional data inside them if you use generic FaultException type.I.e. FaultException<FaultInfo>
where FaultInfo
is your class that stores additional exception data. Don't forget to add data contract serialization attributes onto class properties.
Also, you should apply FaultContract attributes on methods that are supposed to throw FaultExceptions of your kind.
[OperationContract]
[FaultContract(typeof(FaultInfo))]
void DoSomething();
这篇关于从WCF捕获自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!