Поделиться через


HandleErrorAttribute Class

Represents an attribute that is used to handle an exception that is thrown by an action method.

Inheritance Hierarchy

System.Object
  System.Attribute
    System.Web.Mvc.FilterAttribute
      System.Web.Mvc.HandleErrorAttribute

Namespace:  System.Web.Mvc
Assembly:  System.Web.Mvc (in System.Web.Mvc.dll)

Syntax

'Declaration
<AttributeUsageAttribute(AttributeTargets.Class Or AttributeTargets.Method, Inherited := True,  _
    AllowMultiple := True)> _
Public Class HandleErrorAttribute _
    Inherits FilterAttribute _
    Implements IExceptionFilter
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method, Inherited = true, 
    AllowMultiple = true)]
public class HandleErrorAttribute : FilterAttribute, 
    IExceptionFilter
[AttributeUsageAttribute(AttributeTargets::Class|AttributeTargets::Method, Inherited = true, 
    AllowMultiple = true)]
public ref class HandleErrorAttribute : public FilterAttribute, 
    IExceptionFilter

The HandleErrorAttribute type exposes the following members.

Constructors

  Name Description
Public method HandleErrorAttribute Initializes a new instance of the HandleErrorAttribute class.

Top

Properties

  Name Description
Public property ExceptionType Gets or sets the type of the exception.
Public property Master Gets or sets the master view for displaying exception information.
Public property Order Gets or sets the order in which the action filters are executed. (Inherited from FilterAttribute.)
Public property TypeId Gets the unique identifier for this attribute. (Overrides Attribute.TypeId.)
Public property View Gets or sets the page view for displaying exception information.

Top

Methods

  Name Description
Public method Equals Infrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCode Returns the hash code for this instance. (Inherited from Attribute.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method IsDefaultAttribute When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public method Match When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method OnException Called when an exception occurs.
Public method ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Explicit Interface Implementations

  Name Description
Explicit interface implemetationPrivate method _Attribute.GetIDsOfNames Maps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetationPrivate method _Attribute.GetTypeInfo Retrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetationPrivate method _Attribute.GetTypeInfoCount Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetationPrivate method _Attribute.Invoke Provides access to properties and methods exposed by an object. (Inherited from Attribute.)

Top

Remarks

The HandleErrorAttribute attribute in ASP.NET MVC lets you specify how to handle an exception that is thrown by an action method. By default, when an action method with the HandleErrorAttribute attribute throws any exception, MVC displays the Error view that is located in the ~/Views/Shared folder.

This topic contains the following sections:

  • Setting HandleErrorAttribute Properties

  • Specifying the Order Property

  • Accessing Exception Data in the View

  • Enabling Custom Error Handling

  • Handling Errors in the Error View

Setting HandleErrorAttribute Properties

You can modify the default behavior of the HandleErrorAttribute filter by setting the following properties:

  • ExceptionType. Specifies the exception type or types that the filter will handle. If this property is not specified, the filter handles all exceptions.

  • View. Specifies the name of the view to display.

  • Master. Specifies the name of the master view to use, if any.

  • Order. Specifies the order in which the filters are applied, if more than one HandleErrorAttribute filter is possible for a method.

Specifying the Order Property

The Order property of the HandleErrorAttribute attribute helps determine which HandleErrorAttribute filter is used to handle an exception. You can set the Order property to an integer value that specifies a priority from -1 (highest priority) to any positive integer value. The greater the integer value is, the lower the priority of the filter is. The Order property follows these rules:

  1. Filters that are applied to a controller automatically apply to every action method in that controller.

  2. Filters that are applied to the controller run before filters that are applied to an action method, as long as the order numbers are the same.

  3. Filters with the same order number are applied in an undetermined order.

  4. If no order number is specified, the order number is -1. This means that the filter is applied before any other HandleErrorAttribute filters, except other filters whose order is also -1.

  5. The first HandleErrorAttribute filter that can handle the exception will be called, after which exception handling stops for that exception.

Accessing Exception Data in the View

The MVC framework passes information about an exception to the error view in the ViewDataDictionary object whose Model property is set to an instance of the ExceptionContext class. The ViewData dictionary contains values for the following keys:

  • ActionName. The intended action method.

  • ControllerName. The intended controller.

  • Exception. The exception object.

Enabling Custom Error Handling

To enable custom error handling for use by a HandleErrorAttribute filter, add a customErrors element to the system.web section of the application's Web.config file, as shown in the following example:

<system.web>
  <customErrors mode="On" defaultRedirect="Error" />
</system.web>

Handling Errors in the Error View

Errors can occur in the error view itself. In that case, the default ASP.NET error page is displayed. To avoid this, you can configure the application to display an error file in the customErrors section of the Web.config file, as shown in the following example:

<system.web>
  <customErrors mode="On" defaultRedirect="GenericErrorPage.htm">
    <error statusCode="500" redirect="/Error.htm" />
  </customErrors>
</system.web>

Examples

The following example shows how to use the HandleErrorAttribute class to customize error handling for controllers and action methods. In the example, the HomeController class includes the ThrowException action method, which throws an ApplicationException error. This method is marked with a HandleErrorAttribute attribute that has no parameters. When the method is called, the ThrowException method throws an exception and the default Error view is displayed.

The ThrowNotImplemented method is marked with a HandleErrorAttribute attribute that has two parameters. The View parameter specifies which CustomErrorView instance to display. The ExceptionType parameter specifies that this filter should be called only for a NotImplementedException error.

The Order parameter of the HandleErrorAttribute attribute for the controller has been set to 2. This means that it will be called only if an exception occurs in the Index or About methods.

This example also shows the content of CustomErrorView and CustomError.Master, views, and shows an updated Index view. CustomErrorView displays information about the exception, such as the name of the controller and action method that threw the exception, the exception message, and the stack-trace data.

In this example, the Index view contains links to the ThrowException and ThrowNotImplemented methods.

The following example shows the HomeController class.

<HandleError(Order:=2)> _
Public Class HomeController
    Inherits System.Web.Mvc.Controller

    Function Index() As ActionResult
        ViewData("Message") = "Welcome to ASP.NET MVC!"

        Return View()
    End Function

    Function About() As ActionResult
        Return View()
    End Function

    <HandleError()> _
    Public Function ThrowException() As ActionResult
        Throw (New ApplicationException())
    End Function

    <HandleError(View:="CustomErrorView", ExceptionType:=GetType(NotImplementedException))> _
    Public Function ThrowNotImplemented() As ActionResult
        Throw (New NotImplementedException())
    End Function
End 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();
    }
}

The following example shows the CustomErrorView view.

<h2>CustomErrorView</h2>
<p>
  Controller: <%=CType(ViewData.Model, HandleErrorInfo).ControllerName%>
</p>
<p>
  Action: <%=CType(ViewData.Model, HandleErrorInfo).ActionName%>
</p>
<p>
  Message: <%=CType(ViewData.Model, HandleErrorInfo).Exception.Message%>
</p>
<p>
  Stack Trace: <%=CType(ViewData.Model, HandleErrorInfo).Exception.StackTrace%>
</p>
<h2>CustomErrorView</h2>
<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>

The following example shows the CustomError master view.

The following example shows the Index view.

<h2><%= Html.Encode(ViewData("Message")) %></h2>
<%= Html.ActionLink("Throw An Exception", "ThrowException")%> (Default Error Page)
<br /><br />
<%= Html.ActionLink("Throw Not Implemented Exception", "ThrowNotImplemented")%> (Custom Error Page)
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<%= Html.ActionLink("Throw An Exception", "ThrowException")%> (Default Error Page)
<br /><br />
<%= Html.ActionLink("Throw Not Implemented Exception", "ThrowNotImplemented")%> (Custom Error Page)

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

System.Web.Mvc Namespace

Other Resources

Extending Metadata Using Attributes