从FaultException获取真正的异常<>

时间:2014-05-30 13:21:58

标签: c# .net exception exception-handling

我在调用服务API时抓住FaultException,例如

catch(FaultException<MyCustomEx> e)
{
    // How do I get the MyCustomEx object here?
}

我想在嵌入其中的MyCustomEx对象上调用一些方法。

e.getTheActualExc().getMyCustomErrorCode();

如何获得实际对象?

3 个答案:

答案 0 :(得分:8)

根据

http://msdn.microsoft.com/ru-ru/library/ms576199(v=vs.110).aspx

所需的属性为Detail

try {
  ...
}
catch(FaultException<MyCustomEx> e) {
  MyCustomEx detail = e.Detail;
  ...
}

或者,如果您必须捕获FaultException类,则可以使用 Reflection

  try {
    ...
  }
  catch (FaultException e) {
    PropertyInfo pi = e.GetType().GetProperty("Detail");

    if (pi != null) {
      Object rawDetail = pi.GetValue(e); 

      MyCustomEx detail = rawDetail as MyCustomEx;

      if (detail != null) {
        ...
      }
      ...
    }
    ...
  }

答案 1 :(得分:2)

e.Detail属性将为您提供FaultException对象&lt;&gt; ,请参阅MSDN

答案 2 :(得分:1)

var serviceFault = exc as FaultException<ExceptionDetail>;

        if (serviceFault != null)
        {
            if (serviceFault.Detail.Type.Equals(typeof(TimeoutException).FullName))
            {

            }
            else if serviceFault.Detail.Type.Equals(typeof(EndpointNotFoundException).FullName))
            {

            }
            .....
        }

这是我使用的一个例子。您可以访问Detail

中的类型