使用不同的方法和参数捕获基类中的派生类异常

时间:2016-08-15 08:25:12

标签: c# asp.net-mvc

我试图制作像base"异常处理程序"事情。因此,当派生类中的任何方法(具有任意数量的参数)被调用时,此基类将尝试捕获异常。我不善于用文字描述这个,所以这里是场景:

public abstract BaseClass
{
    Exception _ex;

    public Exception LastKnownException
    {
        get
        {
            return this._ex;
        }
    }

    //...
    //what do I do here to assign the value of above property when some random exception occur in derived class?
    //...

    //The closest I can get...
    public void RunMethod(Action method)
    {
        try
        {
            method.Invoke();
        }
        catch (Exception ex)
        {
            this._ex = ex;
        }
    }
}

public class DerivedClass : BaseClass
{   
    public void DoRandomMethod(int couldBeOfAnyTypeHere, bool andIndefiniteNumberOfThese)
    {
        bool result = false;
        var someObject = new OtherClass(couldBeOfAnyTypeHere, out andIndefiniteNumberOfThese);

        someObject.DoInternalWork(result); // <-- here is where I need the base class to take care if any exception should occur
    }

    public int AnotherMethod(int? id)
    {       
        if (!id.HasValue) 
            id = Convert.ToInt32(Session["client_id"]);

        var someOtherObject = new OtherClassB(id.Value);

        return someOtherObject.CheckSomething(); // <-- and catch possible exceptions for this one too
    }

    //The closest I can get... (see base class implementation)
    public List<RandomClass> GetSomeListBy(int id)
    {
        RunMethod(() => 
            string[] whateverArgs = new[] { "is", "this", "even", "possible?" };

            YetAnotherStaticClass.GetInstance().ExecuteErrorProneMethod(whateverArgs); // <-- Then when something breaks here, the LastKnownException will have something
        );
    }
}

public class TransactionController : Controller
{
    public ActionResult ShowSomething()
    {
        var dc = new DerivedClass();

        dc.DoRandomMethod(30, true);

        if (dc.LastKnownException != null)
        {
            //optionally do something here
            return RedirectToAction("BadRequest", "Error", new { ex = dc.LastKnownException });
        }
        else
        {
            return View();
        }       
    }
}

编辑:我的简单方法是有效的,但是,我不想一直用这个lambda驱动的RunMethod()方法包装所有方法 - 我需要基类以某种方式拦截任何传入的异常并将Exception对象返回到派生类而不抛出错误。

任何想法都将不胜感激。并提前感谢!

2 个答案:

答案 0 :(得分:1)

我认为您应该考虑使用事件System.AppDomain.UnhandledException

每当发生未处理的异常时,都会引发此事件。

由于您不会将代码与异常的可能性混为一谈,因此您的代码将更易于阅读。除此之外,它还可以为派生类提供捕获异常的机会,如果他们期望异常,而不会干扰您的自动异常捕获器。

您的设计是这样的,如果有人调用派生类的多个函数,然后检查是否有任何异常,调用者将不知道哪个函数导致了异常。我假设您的调用者对哪个函数导致异常并不感兴趣。如果您只想记录异常,直到有人调查它们,通常会出现这种情况。

如果是这种情况,请考虑采取以下措施:

static void Main(string[] args)
{
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    var ex = e.ExceptionObject as Exception;
    if (ex != null)
        logger.LogException(ex);
    // TODO: decide whether to continue or exit.
}

如果你真的只想为你的抽象基类

这样做
public abstract BaseClass
{
    private List<Exception> unhandledExceptions = new List<Exception>();

    protected BaseClass()
    {
        AppDomain.CurrentDomain.UnhandledException += UnhandledException;
    }

private void UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    var ex = e.ExceptionObject as Exception;
    if (ex != null)
        this.UnhandledExceptions.Add(ex);
}

public List<Exception> LastKnownExceptions
{
    get { return this.unhandledExceptions; }
}

答案 1 :(得分:1)

我对捕获异常有类似的要求,但是使用了一个特定的实现(即不是抽象类)来封装错误的处理。

请注意,这会引入任何预期异常的参数(params Type [] catchableExceptionTypes),但您当然可以根据自己的要求进行修改。

public class ExceptionHandler
{
    // exposes the last caught exception
    public Exception CaughtException { get; private set; }

    // allows a quick check to see if an exception was caught
    // e.g. if (ExceptionHandler.HasCaughtException) {... do something...}
    public bool HasCaughtException { get; private set; }

    // perform an action and catch any expected exceptions
    public void TryAction(Action action, params Type[] catchableExceptionTypes)
    {
        Reset();
        try
        {
            action();
        }
        catch (Exception exception)
        {
            if (ExceptionIsCatchable(exception, catchableExceptionTypes))
            {
                return;
            }
            throw;
        }
    }

    // perform a function and catch any expected exceptions
    // if an exception is caught, this returns null
    public T TryFunction<T>(Func<T> function,  params Type[] catchableExceptionTypes) where T : class
    {
        Reset();
        try
        {
            return function();
        }
        catch (Exception exception)
        {
            if (ExceptionIsCatchable(exception, catchableExceptionTypes))
            {
                return null;
            }
            throw;
        }
    }

    bool ExceptionIsCatchable(Exception caughtException, params Type[] catchableExceptionTypes)
    {
        for (var i = 0; i < catchableExceptionTypes.Length; i++)
        {
            var catchableExceptionType = catchableExceptionTypes[i];
            if (!IsAssignableFrom(caughtException, catchableExceptionType)) continue;
            CaughtException = caughtException;
            HasCaughtException = true;
            return true;
        }
        return false;
    }

    static bool IsAssignableFrom(Exception exception, Type type)
    {
        if (exception.GetType() == type) return true;
        var baseType = exception.GetType().BaseType;
        while (baseType != null)
        {
            if (baseType == type) return true;
            baseType = baseType.BaseType;
        }
        return false;
    }

    void Reset()
    {
        CaughtException = null;
        HasCaughtException = false;
    }
}