Get the App
SLTechnology News&Howtos  ›  Development  › 

Methods and steps of ASP.NET mvc exception handling

Shulou Source: shulou.com Published: 2022-06-03 08:05:29 09月19日 Update

This article mainly explains "methods and steps of ASP.NET mvc exception handling". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "the methods and steps of ASP.NET mvc exception handling".

1. First of all, it is common to save exception classes (that is, write exception information to a file)

The copy code is 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. Exception handling of controller

In this way, you can override the OnException () method in the controller that requires exception handling, because it inherits the IExceptionFilter interface.

The copy code is 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

The copy code is as follows:

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 ()

}

}

At this point, I believe you have a deeper understanding of the "methods and steps of ASP.NET mvc exception handling". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Processing code method step content filter learning practical deeper information interest practicality practicality that is common interface controller simple operation file way Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB NVidia vpn Microsoft MySQL