asp.net MVC exception Handling Method Example Introduction _ Practical Tips

Source: Internet
Author: User
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 ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.