1. The first common class to hold exceptions (that is, to write exception information to a file)
Copy Code code as follows:
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 overrides the Onexception () method in a controller that requires exception handling because it inherits the Iexceptionfilter interface
Copy Code code as follows:
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
Copy Code code as follows:
namespace Mymvc.controllers
{
public class Exceptioncontroller:c Ontroller
{
[Error]
Public actionresult Index ()
{
throw new Exception ("Filter Exception! ");
}
}
}
public class Errorattribute:handleerrorattribute
{
public override void Onexcept Ion (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 ();
}
}