65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 LinFu.AOP 2.0 动态拦截抛出的异常

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2011年5月4日

LGPL3

2分钟阅读

viewsIcon

7843

如何使用 LinFu.AOP 2.0 动态拦截抛出的异常

exception

LinFu 动态捕获抛出异常的截图

出错时,继续拦截

LinFu.AOP 的另一个有用功能是在运行时拦截(并重新抛出)应用程序中的异常。事实上,LinFu 使其变得非常容易,你只需要在 CSProj 文件中添加以下几行代码

<PropertyGroup>
  <PostWeaveTaskLocation>
    $(MSBuildProjectDirectory)\$(OutputPath)\..\..\..\lib\LinFu.Core.dll
  </PostWeaveTaskLocation>
</PropertyGroup>
<UsingTask TaskName="PostWeaveTask" AssemblyFile="$(PostWeaveTaskLocation)" />
<Target Name="AfterBuild">
  <PostWeaveTask TargetFile="$(MSBuildProjectDirectory)\$(OutputPath)$(MSBuildProjectName).dll" 
                 InterceptAllExceptions="true" />
</Target>

异常简单

要使用 LinFu.AOP 的动态异常处理功能,你只需要进行以下调用来处理应用程序中抛出的所有异常

public class SampleExceptionHandler : IExceptionHandler
{
    public bool CanCatch(IExceptionHandlerInfo exceptionHandlerInfo)
    {
        return true;
    }

    public void Catch(IExceptionHandlerInfo exceptionHandlerInfo)
    {
        var exception = exceptionHandlerInfo.Exception;
        Console.WriteLine("Exception caught: {0}", exception);

        // This line tells LinFu.AOP to swallow the thrown exception;
        // By default, LinFu will just rethrow the exception
        exceptionHandlerInfo.ShouldSkipRethrow = true;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Hook the sample exception handler into the application
        ExceptionHandlerRegistry.SetHandler(new SampleExceptionHandler());

        var account = new BankAccount(100);

        // Without LinFu's dynamic exception handling, the 
        // next line of code will cause the app to crash:
        account.Deposit(100);

        return;
    }
}

试着捕获我,如果你能的话

ExceptionHandlerRegistry.SetHandler 的调用告诉 LinFu 将 SampleExceptionHandler 挂钩到你的应用程序中,以便抛出的所有异常都将自动由给定的异常处理程序处理。在正常情况下(拦截被禁用时),对 account.Deposit() 的调用将导致应用程序崩溃,但 正如这个例子所示LinFu.AOP 能够在异常抛出之前拦截它,从而避免应用程序崩溃。

然而,更令人感兴趣的是描述异常抛出上下文的 IExceptionHandlerInfo 实例

public interface IExceptionHandlerInfo
{
    Exception Exception { get; }
    IInvocationInfo InvocationInfo { get; }
    object ReturnValue { get; set; }
    bool ShouldSkipRethrow { get; set; }
}

比抛出异常更多的信息

IExceptionHandlerInfo 接口包含足够的信息来描述导致异常的方法,并且具有诸如 ShouldSkipRethrow 之类的属性,允许你决定 LinFu 是否应该直接吞噬异常并继续运行程序,就好像从未抛出异常一样。ReturnValue 属性反过来允许你更改给定方法的返回值,以防你想恢复该方法并提供替代返回值,就好像从未抛出异常一样。

正如你所看到的,LinFu.AOP 使透明地处理应用程序中的异常变得非常容易,如果这篇文章至少能为一些开发人员避免手动诊断应用程序的头痛,那么我会认为这是一个令人满意的成功。

尽情享用!

编辑:你可以在 这里 获取 LinFu.AOP 动态异常处理的代码示例。

© . All rights reserved.