通过多态进行异常处理

问题描述

| 我需要在本设计中提出的处理异常的观点。 我有一个wcf服务,它会引发不同类型的故障异常: 抛出新的FaultException (...) 抛出新的FaultException (...) ... ... 所有这些故障异常类都实现了一个称为IViolationFault的接口,该接口具有单个HandleException方法。每个此类方法的实现因它们所在的类而异。因此,例如,当这些异常类在客户端中被捕获时,我所要做的只是调用那个HandleException()方法,它将无需我编写IF条件来区分错误类型就可以解决。在BusinessRuleViolationFault \的HandleException()方法中,我可能只想在屏幕上显示一条消息,而在另一个方法中,我可能想将其记录在某处并触发其他操作...
catch (FaultException<BusinessRuleViolationFault> ex)
 {
ex.HandleException();
 }
catch (FaultException<SomeOtherViolationFault> ex)
 {
ex.HandleException();
 }
问题 这有什么问题吗 方法? 有什么办法可以减少 捕获块的数量 一个catch块可以处理所有异常类型? 这是在处理异常时实现多态性的一种很好的面向对象的方法吗? 编辑 香港专业教育学院更改代码从基类继承而不是实现接口。我的BusinessRuleViolationFault类具有HandleException方法,但是我无法在客户端catch块中获取HandleException方法。怎么了?这就是它在服务中的抛出方式
BusinessRuleViolationFault bf = new BusinessRuleViolationFault(\"\");
throw new FaultException<BusinessRuleViolationFault>(bf,new FaultReason(new FaultReasonText(\"Fault reason here\")));
这是我的BusinessRuleViolationFault代码
[DataContract]
public class BusinessRuleViolationFault : BaseFault
{
    public BusinessRuleViolationFault(string message)
        : base(message)
    {

    }


    [OperationContract]
    public override string HandleException()
    {
        return \"BusinessRuleViolationFault executed\";
    }
}



[DataContract]
public abstract class BaseFault
{
    public BaseFault(string message)
    {
        Message = message;
    }

    [DataMember]
    public string Message { get; set; }

    [OperationContract]
    public abstract string HandleException();
}
让我对此有您的想法。谢谢你的时间...     

解决方法

        编辑:正确的示例代码。 至少对于WCF(这是实现自定义错误的方法)而言,这样做是没有错的。虽然,您失去了多态性,因为您无法做到这样
// Does not work
try
{
}
catch (FaultException<IVoliationFault> ex)
{
  ex.HandleException();
}
捕获您的FaultExceptions。 您(显然)也不能将基类
System.ServiceModel.FaultException<TDetail>
甚至
System.ServiceModel.FaultException
更改为包含任何
HandleException()
方法。 您可以做的是,通过反射来提取FaultException的“ 7”,如果有的话,然后进行处理:
        try
        {
        }
        catch (FaultException ex)
        {
            var detail = ex.GetDetail<IViolationFault>(); // EDIT: Specify type

            if (detail != null)
            {
                detail.HandleException();
            }
            else
            {
                // Either not a FaultException<TDetail>,or not FaultException<IViolationFault>.
                throw;
            }
        }
...

public static class FaultExceptionExtensions
{
    public static T GetDetail<T>(this FaultException exception)
    {
        if (exception == null)
            throw new ArgumentNullException(\"exception\");

        Type type = exception.GetType(); // EDIT: use \"exception\" instead of \"ex\"
        if (!type.IsGenericType)
        {
            return default(T);
        }

        Type genType = type.GetGenericArguments()[0];

        PropertyInfo pi = type.GetProperty(\"Detail\",genType);
        Debug.Assert(pi != null,\"FaultException<\" + genType + \">.Detail property is missing\");

        object val = pi.GetValue(exception,null);

        if (!typeof(T).IsInstanceOfType(val))
        {
            return default(T);
        }

        return (T)val;
    }

}
    ,        这种方法没有错,只是多态性的正常使用。 您可以通过使所有自定义异常类都派生自基本异常类而不是仅实现接口来减少catch块的数量。例如:
public abstract class FaultException : Exception
{
    public abstract void HandleException()
}

public class Faultexception<T> : FaultException
{
     public override void HandleException()
     {
      //your code here
     }
}
这样,您可以通过以下方式捕获所有异常:
catch (FaultException ex) 
{
     ex.HandleException();
}
    ,        您可能想看一下这篇博客文章中记录的功能方法,该方法可以使您的try / catch逻辑更加清晰/简洁。 例如:
TryCatch.Try(() =>
         {
             using (var stream = File.OpenRead(FileTextBox.Text))
             {
                 Trace.WriteLine(stream.Length);
             }
         })
.Catch<FileNotFoundException,DirectoryNotFoundException,UnauthorizedAccessException>
    (ex =>
    {
        MessageBox.Show(ex.Message,\"Fail\");
    });