In ASP. net mvc, we can use the HandleErrorAttribute feature to specify how to handle the exception thrown by the Action. if HandleErrorAttribute is set for an Action, MVC displays the Error view when an exception is thrown ~ /Views/Shared directory.
Set HandleError attributes
You can set the following attributes to change the default processing of the HandleErrorAttribute feature:
ExceptionType. specify the types of exceptions that the filter can handle. If this attribute is not specified, the filter will handle all exceptions.
View. Specify the View name to be displayed by the filter when an exception occurs.
Master. specify the name of the view Master, if any.
Order. Specify the application Order of the filter. If an Action has multiple HandleErrorAttribute filters.
Specify the Order attribute
If an Action sets multiple HandleErrorAttribute, the Order attribute can be used to determine which filter to use. the value can be set to an integer from-1 (highest priority) to any positive integer to identify its priority. The larger the value, the lower the priority level. the Order attribute follows the following rules:
Filters applied to the Controller are automatically applied to all actions of the Controller.
If HandleErrorAttribute is applied to both the Controller and Action, as long as the Order attribute value is the same, the filter on the Controller will be executed before the filter on the Action will be executed.
For filters with the same Order attribute, their execution Order is not fixed.
If the Order attribute is not specified, the default value is-1, which means that the filter will take precedence over other filters unless other filters specify Order as-1.
If multiple filters are available, the first filter that can handle the exception will be called first, and the processing of the exception will end.
Get exception information in View
The ASP. net mvc Framework stores exception information in ViewDataDictionary and passes it to the Error view. The Model attribute of this ViewDataDictionary is an instance of the predictioncontext class. This ViewData has the following keys:
ActionName: name of the target Action Method
ControllerName: name of the Target Controller
Exception: Exception object.
Enable custom error handling
Next, enable custom error processing for the HandleErrorAttribute filter, open the Web. config file of the program, and add a customErrors element in the system. web Section, as shown below:
<System. web>
<CustomErrors mode = "On" defaultRedirect = "Error"/>
</System. web>
Handle errors in the Error View
Sometimes an Error occurs in the Error view. ASP. NET will display its default error page (yellow-red text), to avoid this situation, we in the Web. the custom error page in the customErrors section of the config file is as follows:
<System. web>
<CustomErrors mode = "On" defaultRedirect = "GenericErrorPage.htm">
<Error statusCode = "500" redirect = "/Error.htm"/>
</CustomErrors>
</System. web>
Sample program
The following example shows how to customize Exception Handling for the HandleErrorAttribute feature of the Controller and Action applications.
In this example, HomeController has an Action method named ThrowException. In this Action, an ApplicationException type error is thrown. This Action applies handleerrorattrition, but does not set any parameters. when this Action is executed, an exception is thrown and the default Error view is displayed.
The ThrowNotImplemented method applies handleerrorattrited with two parameters. The View parameter specifies the custom Error View name: CustomErrorView. The ExceptionType parameter specifies that the filter only handles exceptions of the ThrowNotImplemented type.
The HandleErrorAttribute of Controller sets the Order parameter to 2, which means that the filter will only be executed when an exception occurs in the Index or About method.
At the same time, the examples show the contents of the view CustomErrorView and CustomError. Master.
View CustomErrorView displays the exception information, such as the name of the Controller and Action that throw the exception, the exception content, and stack trace information.
The View Index has two links pointing to two actions: ThrowException and ThrowNotImplemented.
HomeController class
[HandleError (Order = 2)]
Public class HomeController: Controller
{
Public ActionResult Index ()
{
ViewData ["Message"] = "Welcome to ASP. net mvc! ";
Return View ();
}
Public ActionResult About ()
{
Return View ();
}
[HandleError]
Public ActionResult ThrowException ()
{
Throw new ApplicationException ();
}
[HandleError (View = "CustomErrorView", ExceptionType = typeof (NotImplementedException)]
Public ActionResult ThrowNotImplemented ()
{
Throw new NotImplementedException ();
}
}
View CustomErrorView
<Asp: Content ID = "Content1" ContentPlaceHolderID = "TitleContent" runat = "server">
CustomErrorView
</Asp: Content>
<Asp: Content ID = "Content2" ContentPlaceHolderID = "MainContent" runat = "server">
<H2> CustomErrorView <P>
Controller: <% = (HandleErrorInfo) ViewData. Model). ControllerName %>
</P>
<P>
Action: <% = (HandleErrorInfo) ViewData. Model). ActionName %>
</P>
<P>
Message: <% = (HandleErrorInfo) ViewData. Model). Exception. Message %>
</P>
<P>
Stack Trace: <% = (HandleErrorInfo) ViewData. Model). Exception. StackTrace %>
</P>
</Asp: Content>
View Index
<Asp: Content ID = "indexTitle" ContentPlaceHolderID = "TitleContent" runat = "server">
Home Page
</Asp: Content>
<Asp: Content ID = "indexContent" ContentPlaceHolderID = "MainContent" runat = "server">
<H2> <% = Html. Encode (ViewData ["Message"]) %> <% = Html. ActionLink ("Throw An Exception", "ThrowException") %> (Default Error Page)
<Br/>
<% = Html. ActionLink ("Throw Not Implemented Exception", "ThrowNotImplemented") %> (Custom Error Page)
</Asp: Content>
Master page CustomError. Master
<% @ Master Language = "C #" Inherits = "System. Web. Mvc. ViewMasterPage" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> <asp: ContentPlaceHolder ID = "TitleContent" runat = "server"/> </title>
<Link href = "http://www.cnblogs.com/Content/Site.css" rel = "stylesheet" type = "text/css"/>
<Style type = "text/css">
Body. error
{
Background-color: Maroon;
Color: #696969;
}
</Style>
</Head>
<Body class = "error">
<Div class = "page">
<Div id = "header">
<Div id = "title">
<H1> A Custom Error Occurred </Div>
<Div id = "logindisplay">
<% Html. RenderPartial ("LogOnUserControl"); %>
</Div>
<Div id = "menucontainer">
<Ul id = "menu">
<Li> <% = Html. ActionLink ("Home", "Index", "Home") %> </li>
<Li> <% = Html. ActionLink ("About", "About", "Home") %> </li>
</Ul>
</Div>
</Div>
<Div id = "main">
<Asp: ContentPlaceHolder ID = "MainContent" runat = "server"/>
<Div id = "footer">
</Div>
</Div>
</Div>
</Body>
</Html>