【发布时间】:2015-10-16 18:26:29
【问题描述】:
我有一个 WCF 服务,我在其中实现了自定义服务故障。我基于特定条件抛出错误,所以在 if 语句中我抛出下面的错误。
throw new FaultException<CustomServiceFault>(
new CustomServiceFault
{
ErrorMessage = string.Format(
"Error in response, code:{0} message:{1}",
response.Error.Code,
response.Error.Message),
Source = "ConnectToOpenLdap Method",
StackTrace = string.Format(
"Error in response, code:{0} message:{1}",
response.Error.Code,
response.Error.Message)
},
new FaultReason(
string.Format(CultureInfo.InvariantCulture, "{0}", "Service fault exception")));
在 catch 中,我像这样重新抛出异常:
catch (Exception exception)
{
var customServiceFault = GetCustomException(exception);
throw new FaultException<CustomServiceFault>(
customServiceFault,
new FaultReason(customServiceFault.ErrorMessage),
new FaultCode("Sender"));
}
GetCustomException() 方法只是将异常转换为我的自定义异常对象。
问题是传递给 GetCustomException() 的异常在 InnerException 属性中没有详细信息。我看到的截图:
如何提取或获取我在 if 条件中抛出异常时设置的自定义 ErrorMessage、Source 等?正如您在屏幕截图中看到的,扩展“异常”显示了对象类型(我相信),并且在“详细信息”内部显示了 ErrorMessage、InnerExceptionMesage、Source 和 StackTrace。这就是我所追求的。如何在 GetCustomException() 方法中提取这些值?
这是 GetCustomException() 方法:
private static CustomServiceFault GetCustomException(Exception exception)
{
var customServiceFault = new CustomServiceFault
{
ErrorMessage = exception.Message,
Source = exception.Source,
StackTrace = exception.StackTrace,
Target = exception.TargetSite.ToString()
};
return customServiceFault;
}
CustomServiceFault 类:
[DataContract]
public class CustomServiceFault
{
[DataMember]
public string ErrorMessage { get; set; }
[DataMember]
public string StackTrace { get; set; }
[DataMember]
public string Target { get; set; }
[DataMember]
public string Source { get; set; }
[DataMember]
public string InnerExceptionMessage { get; set; }
}
【问题讨论】:
-
能否添加您的 CustomServiceFault 类?
-
用
FaultException<CustomServiceFault>代替Exception。然后,您可以更改GetCustomException()方法的类型。然后,您可以访问Details属性。您也可以通过类型转换来完成此操作。但是,当您计划处理这些类型时,最好捕获特定的异常类型。 -
我添加了 CustomServiceFault 类
标签: c# wcf exception-handling