如何获取异常详细信息
问题描述:
我有一个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属性中的细节。的我所看到的截图:
我如何提取或获取定制的ErrorMessage,来源等我的,如果条件抛出异常时设定?正如你在截图中看到的,扩展的“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;
}
请问您可以添加您的CustomServiceFault类吗? – Lorek
而不是'Exception',赶上'FaultException'。然后,您可以更改'GetCustomException()'方法的类型。然后,你可以访问'Details'属性。你也可以通过类型转换来实现这一点。但是当你打算处理这些类型时,最好捕获特定的异常类型。 –
Lorek
我加了CustomServiceFault类 – obautista