欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET mvc异常处理的方法示例介绍

程序员文章站 2024-02-26 10:01:40
1.首先常见保存异常的类(就是将异常信息写入到文件中去) 复制代码 代码如下: public class logmanager { private string logfi...
1.首先常见保存异常的类(就是将异常信息写入到文件中去)
复制代码 代码如下:

public class logmanager
{
private string logfilepath = string.empty;
public logmanager(string logfilepath)
{
this.logfilepath = logfilepath;
fileinfo file = new fileinfo(logfilepath);
if (!file.exists)
{
file.create().close();
}
}
public void savelog(string message, datetime writertime)
{
string log = writertime.tostring() + ":" + message;
streamwriter sw = new streamwriter(logfilepath, true);
sw.writeline(log);
sw.close();
}
}

2、控制器异常处理

这种方式就在需要进行异常处理的controller中重写onexception()方法即可,因为它本身继承了iexceptionfilter接口
复制代码 代码如下:

public class exceptioncontroller : controller
{
public actionresult index()
{
throw new exception("我抛出异常了!");
}
protected override void onexception(exceptioncontext filtercontext)
{
string filepath = server.mappath("~/exception。txt");
streamwriter sw = system.io.file.appendtext(filepath);
sw.writeline(datetime.now.tostring() + ":" + filtercontext.exception.message);
sw.close();
base.onexception(filtercontext);
redirect("/");
}
}

3、过滤器异常处理
复制代码 代码如下:

namespace mymvc.controllers
{
public class exceptioncontroller : controller
{
[error]
public actionresult index()
{
throw new exception("过滤器异常!");
}
}
}
public class errorattribute : handleerrorattribute
{
public override void onexception(exceptioncontext filtercontext)
{
base.onexception(filtercontext);
string path = filtercontext.httpcontext.server.mappath("~/exception.txt");
streamwriter sw = system.io.file.appendtext(path);
sw.writeline(datetime.now.tostring()+":"+filtercontext.exception.message);
sw.close();
}
}