当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET mvc异常处理的方法示例介绍

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

他们吉他谱,福建电大形成性测评系统,赵沁心

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();
}
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网