.NET Tips and Tricks

Blog archive

Stacking Up Error Handlers in ASP.NET

If you add multiple HandleError attributes to an ASP.NET MVC Controller method or class, each HandleError can target a specific exception and send the user a different View. The following example assigns custom Views to two exceptions (ArithmeticException and DivideByZeroException). For any other Exception, the user is sent the default Error View:

<HandleError(exceptiontype:=GetType(DivideByZeroException), Order:=99, View:="UserError")>
<HandleError(exceptiontype:=GetType(ArithmeticException),  Order:=50, View:="ProcessError")>
<HandleError()>
Public Class MathController

The problem is that, once ASP.NET MVC finds a HandleError attribute with a matching Exception, MVC ignores the other HandleError attributes, and the default HandleError matches every exception. The code may throw a DivideByZeroException, but if ASP.NET processes the default HandleError attribute (the one that doesn't specify a type) first, ASP.NET will never find the more specific HandleError for the DivideByZeroException. For this plan to work, therefore, I need ASP.NET MVC to process the HandleError attributes in a specific order, beginning with the attributes for the more specific exceptions and going on to the more general ones.

That's where the Order property on the HandleError attribute comes in: if you don't set the Order property, the HandleError attributes are processed in an undetermined order. If you do set the Order property, ASP.NET MVC will process the HandleError attribute with the highest number in the Order property first. Any HandleError attribute whose Order property isn't set is processed after the attributes with their Order property set.

In my example, by giving the HandleError attribute for the DivideByZeroException an Order property with the highest value, I've ensured that it's processed before the HandleError attribute for the ArithmeticException. By not setting the Order property on the default HandleError attribute, I ensure that it's processed only after the more specific HandleError attributes. Just what I want.

Posted by Peter Vogel on 04/04/2014


comments powered by Disqus

Featured

Subscribe on YouTube