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 core MVC 全局過濾器之ExceptionFilter過濾器(1)
- Asp.net Mvc 身份驗證、異常處理、權限驗證(攔截器)實現代碼
- 詳解使用Spring MVC統一異常處理實戰
- springboot springmvc拋出全局異常的解決方法
- ASP.NET MVC異常處理模塊詳解
- MVC異常處理詳解
- ASP.NET MVC下基于異常處理的完整解決方案總結
- 基于SpringMVC的全局異常處理器介紹
- ASP.NET MVC中異常處理&自定義錯誤頁詳析
- ASP.NET MVC中異常Exception攔截的深入理解