我有一个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 (Exception exception)
{
var customServiceFault = GetCustomException(exception);
throw new FaultException<CustomServiceFault>(
customServiceFault,
new FaultReason(customServiceFault.ErrorMessage),
new FaultCode("Sender"));
}
GetCustomException()方法只是将异常转换为我的自定义异常对象。
问题是传递给GetCustomException()的异常没有InnerException属性中的详细信息。我看到的屏幕截图:
如何在if条件中抛出异常时提取或获取自定义的ErrorMessage,Source等?正如您在屏幕截图中看到的那样,扩展“exception”显示了对象类型(我相信),而“Detail”内部显示了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; }
}
答案 0 :(得分:5)
你没有得到InnerExceptionMessage,因为你没有在任何地方设置它。
private static CustomServiceFault GetCustomException(Exception exception)
{
var customServiceFault = new CustomServiceFault
{
ErrorMessage = exception.Message,
Source = exception.Source,
StackTrace = exception.StackTrace,
Target = exception.TargetSite.ToString(),
// You should fill this property with details here.
InnerExceptionMessage = exception.InnerException.Message;
};
return customServiceFault;
}