扔FaultException<CustomFault>这样的时候:
throw new FaultException<CustomFault>(new CustomFault("Custom fault message"));
Run Code Online (Sandbox Code Playgroud)
我得到以下内容:"此错误的创建者未指定原因." 现在根据这篇MSDN文章,一个不需要使用FaultReason
我有以下服务合同:
[OperationContract]
[FaultContract(typeof(CustomFault))]
CustomType[] SomeMethod(int someParameter);
[DataContract]
public class CustomFault
{
private string report;
public CustomFault(string message)
{
this.report = message;
}
[DataMember]
public string Message
{
get { return this.report; }
set { this.report = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
有关MSDN文章的评论表明它必须使用另一个FaultReason,但在其他几个地方,我看到有人认为FaultReason除非必要,否则你不应该使用它.
所以我的问题如下; 是否真的必须使用FaultReason,如果不是 - 我如何防止在尝试抛出时引发的异常FaultException?
编辑
通过从运行示例项目这篇文章中,我得到了excact相同的行为.也许这是由.NET中的更新引起的,文档/样本没有更新.
我已经创建了一个带有服务操作的WCF数据服务.
我想生成一种业务异常.我尝试生成,WebFaultException但我没有看到如何在服务操作抛出此错误时在客户端捕获此错误.
这是我的模拟异常的服务操作:
[WebGet]
public void GenerateException()
{
throw new DataServiceException( 403, "Custom Message" );
}
Run Code Online (Sandbox Code Playgroud)
这是我的客户:
WebClient wc = new WebClient();
wc.DownloadString(
new Uri(
"http://localhost:27820/WcfDataService1.svc/GenerateException"
)
);
Run Code Online (Sandbox Code Playgroud)
DownloadString抛出异常,但它只是Internal Server Error,我看不到我的Custom Message.
任何的想法 ?
非常感谢.
我有一个方法如下:
Public Sub Send()
Dim caughtException As Exception = Nothing
Try
//Attempt action.
Catch ex As Exception //Custom exceptions which can be thrown all inherit from Exception.
//Instantiate error object to be logged.
caughtException = ex
End Try
//Log action and if there is an error log this too.
If caughtException IsNot Nothing Then Throw caughtException
End Sub
Run Code Online (Sandbox Code Playgroud)
我必须记录报告的错误,在研究之后,重新抛出异常是正确的做法.我关心的是保存堆栈信息.
为了保持代码DRY,我将操作记录在一个地方 - 在捕获异常之后.
此功能最终通过WCF公开.