您的位置:首页 > 编程语言 > Java开发

Spring.Net学习系列一: 统一异常处理

2009-12-13 16:43 591 查看
在实际项目中,日志处理是一项常见的功能,如何统一处理异常?

一般的做法是会写个LogProvider类或ILogProvider接口,然后把错误信息通过这个provider写入文件或者数据库等等。

如:

try
{
helloWorld.Show();
}
catch(Exception ex)
{
LogProvider.Write(ex.StackTrace);
MessageBox.show("发生错误");
}

这样会到处充斥着LogProvider.Write(ex.StackTrace);
这样类似的代码,是不是闻到了坏味道?

是的,我们需要想办法放在一个统一的地方,一是代码美观,二是也便于维护。

这个时候我们的Spring.net出马了。利用Spring的AOP,,通过代理,我们可以很方便的统一处理这些异常信息。

当然,异常的记录一般是通过日志模块来处理。所以我们先实现一个日志模块,这里用大名鼎鼎的Log4Net,

稍作封装后,代码如下:

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Spring.Context;
using Spring.Context.Support;
using Log;

namespace LogTest
{
public partial class Form1 : Form
{
private IApplicationContext _ctx;
private IHelloWorld _helloWorld;
public Form1()
{
InitializeComponent();
try
{
helloWorld.Show();
}
catch
{
MessageBox.Show("发生异常");
}
}
private IApplicationContext ctx
{
get
{
if (_ctx == null)
{
_ctx = ContextRegistry.GetContext();
}
return _ctx;
}
}
private IHelloWorld helloWorld
{
get
{
if (_helloWorld == null)
{
_helloWorld = ctx["HelloWorldProxy"] as IHelloWorld;
}
return _helloWorld;
}
}
}
}

。ok大功告成了,看到了吧,代码不记录异常信息时的代码一样,但实现了异常的统计记录,你可以看到在日志文件中已经写入了错误信息。

示例源码点击下载

[下面引用自《Spring 技术手册》]
注意到当异常发生时, Throw Advice 的任务只是执行对应的方法,您并不能在 Throw Advice 中将异常处理掉,在 Throw Advice 执行完毕后,原告的异常仍将传播至应用程序之中, Throw Advice 并不介入应用程序的异常处理,异常处理仍旧是应用程序本身所要负责的,如果想要在 Throw Advice 处理时中止应用程序的处理流程,作法是抛出其它的异常。

运行效果文字描述如下:

程序弹出对话框 “发生异常”

在AppLog.text文件中记录错误信息:

2009-12-13 16:34:17,812 [11] ERROR AppLog [(null)] - Error
System.Exception: 发生异常
在 LogTest.HelloWorld.Show() 位置 F:\Study\LogAop\LogTest\HelloWorld.cs:行号 13
在 _dynamic_LogTest.HelloWorld.Show(Object , Object[] )
在 Spring.Reflection.Dynamic.SafeMethod.Invoke(Object target, Object[] arguments)
在 Spring.Aop.Framework.DynamicMethodInvocation.InvokeJoinpoint()
在 Spring.Aop.Framework.AbstractMethodInvocation.Proceed()
在 Spring.Aop.Framework.Adapter.ThrowsAdviceInterceptor.Invoke(IMethodInvocation invocation)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: