我有一个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; }
}
您没有收到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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句