1.首先常見保存異常的類(就是將異常信息寫入到文件中去)
復(fù)制代碼 代碼如下:
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、控制器異常處理
這種方式就在需要進(jìn)行異常處理的controller中重寫OnException()方法即可,因?yàn)樗旧砝^承了IExceptionFilter接口
復(fù)制代碼 代碼如下:
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、過濾器異常處理
復(fù)制代碼 代碼如下:
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 core MVC 全局過濾器之ExceptionFilter過濾器(1)
- Asp.net Mvc 身份驗(yàn)證、異常處理、權(quán)限驗(yàn)證(攔截器)實(shí)現(xiàn)代碼
- 詳解使用Spring MVC統(tǒng)一異常處理實(shí)戰(zhàn)
- springboot springmvc拋出全局異常的解決方法
- ASP.NET MVC異常處理模塊詳解
- MVC異常處理詳解
- ASP.NET MVC下基于異常處理的完整解決方案總結(jié)
- 基于SpringMVC的全局異常處理器介紹
- ASP.NET MVC中異常處理&自定義錯(cuò)誤頁詳析
- ASP.NET MVC中異常Exception攔截的深入理解