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

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ASP.NET mvc异常处理的方法示例介绍脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
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();
}
}

脚本宝典总结

以上是脚本宝典为你收集整理的ASP.NET mvc异常处理的方法示例介绍全部内容,希望文章能够帮你解决ASP.NET mvc异常处理的方法示例介绍所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:ASP.NETmvc