An example of an ASP. NET mvc exception handling method is presented
- 2020-12-10 00:40:30
- OfStack
1. The first class to save the exception (that is, to write the exception information to a file)
2. Controller exception handling
This approach simply overrides the OnException () method in controller, which requires exception handling, because it inherits the IExceptionFilter interface
3. Filter exception handling
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 exception handling
This approach simply overrides the OnException () method in controller, which requires exception handling, because it inherits the IExceptionFilter interface
public class ExceptionController : Controller
{
public ActionResult Index()
{
throw new Exception(" I threw an 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. Filter exception handling
namespace MyMVC.Controllers
{
public class ExceptionController : Controller
{
[Error]
public ActionResult Index()
{
throw new Exception(" Filter 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();
}
}