<commit_before>---
layout: post
tags: [ASP.NET MVC]
date: 2009-12-01 06:37:01 UTC
title: "Global Error Handling in ASP.NET MVC"
---
{% include JB/setup %}

<div id="post">
	<p>ASP.NET MVC comes with an error-handling feature that enables you to show nice error Views to your users instead of the dreaded Yellow Screen of Death. The most prominently described technique involves attributing either you Controller or a single Controller action, like we see in the AccountController created by the Visual Studio project template.</p> <div style="font-family: consolas; background: white; color: black; font-size: 10pt"> <p style="margin: 0px">[<span style="color: #2b91af">HandleError</span>]</p> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">AccountController</span> : <span style="color: #2b91af">Controller</span> { }</p></div> <p>That sure is easy, but I don't like it for a number of reasons:</p> <ul> <li>Even though you can derive from HandleErrorAttribute, it's impossible to inject any dependencies into Attributes because they must be fully constructed at compile-time. That makes it really difficult to log errors to an interface.  <li>It violates the DRY principle. Although it can be applied at the Controller level, I still must remember to attribute all of my Controllers with the HandleErrorAttribute.</li></ul> <p>Another approach is to override Controller.OnException. That solves the DI problem, but not the DRY problem.</p> <p>Attentive readers may now point out that I can define a base Controller that implements the proper error handling, and require that all my Controllers derive from this base Controller, but that doesn't satisfy me:</p> <p>First of all, it still violates the DRY principle. Whether I have to remember to apply a [HandleError] attribute or derive from a : MyBaseController amounts to the same thing. I (and all my team members) have to remember this always. It's unnecessary project friction.</p> <p>The second thing that bugs me about this approach is that I really do <em>favor composition over inheritance</em>. Error handling is a <em>cross-cutting concern</em>, so why should all my Controllers have to derive from a base controller to enable this? That is absurd.</p> <p>Fortunately, ASP.NET MVC offers a third way.</p> <p>The key lies in the Controller base class and how it deals with IExceptionFilters (which HandleErrorAttribute implements). When a Controller action is invoked, this actually happens through an IActionInvoker. The default ControllerActionInvoker is responsible for gathering the list of IExceptionFilters, so the first thing we can do is to derive from that and override its GetFilters method:</p> <div style="font-family: consolas; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">ErrorHandlingActionInvoker</span> :</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">ControllerActionInvoker</span></p> <p style="margin: 0px">{</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IExceptionFilter</span> filter;</p> <p style="margin: 0px">&nbsp;</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> ErrorHandlingActionInvoker(</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">IExceptionFilter</span> filter)</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (filter == <span style="color: blue">null</span>)</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"filter"</span>);</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p> <p style="margin: 0px">&nbsp;</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.filter = filter;</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p> <p style="margin: 0px">&nbsp;</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">protected</span> <span style="color: blue">override</span> <span style="color: #2b91af">FilterInfo</span> GetFilters(</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">ControllerContext</span> controllerContext,</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">ActionDescriptor</span> actionDescriptor)</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">var</span> filterInfo = </p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">base</span>.GetFilters(controllerContext, </p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; actionDescriptor);</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; filterInfo.ExceptionFilters.Add(<span style="color: blue">this</span>.filter);</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> filterInfo;</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p> <p style="margin: 0px">}</p></div> <p>Here I'm simply injecting an IExceptionFilter instance into this class, so I'm not tightly binding it to any particular implementation  -  it will work with any IExceptionFilter we give it, so it simply serves the purpose of adding the filter at the right stage so that it can deal with otherwise unhandled exceptions. It's pure infrastructure code.</p> <p>Notice that I first invoke base.GetFilters and then add the injected filter to the returned list of filters. This allows the normal ASP.NET MVC IExceptionFilters to attempt to deal with the error first.</p> <p>This ErrorHandlingActionInvoker is only valuable if we can assign it to each and every Controller in the application. This can be done using a custom ControllerFactory:</p> <div style="font-family: consolas; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">ErrorHandlingControllerFactory</span> : </p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">DefaultControllerFactory</span></p> <p style="margin: 0px">{</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: #2b91af">IController</span> CreateController(</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">RequestContext</span> requestContext,</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">string</span> controllerName)</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; {</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">var</span> controller = </p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">base</span>.CreateController(requestContext,</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; controllerName);</p> <p style="margin: 0px">&nbsp;</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">var</span> c = controller <span style="color: blue">as</span> <span style="color: #2b91af">Controller</span>;</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (c != <span style="color: blue">null</span>)</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; c.ActionInvoker = </p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">new</span> <span style="color: #2b91af">ErrorHandlingActionInvoker</span>(</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">new</span> <span style="color: #2b91af">HandleErrorAttribute</span>());</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p> <p style="margin: 0px">&nbsp;</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> controller;</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; }</p> <p style="margin: 0px">}</p></div> <p>Notice that I'm simply deriving from the DefaultControllerFactory and overriding the CreateController method to assign the ErrorHandlingActionInvoker to the created Controller.</p> <p>In this example, I have chosen to inject the HandleErrorAttribute into the ErrorHandlingActionInvoker instance. This seems weird, but it's the HandleErrorAttribute that implements the default error handling logic in ASP.NET MVC, and since it implements IExceptionFilter, it works like a charm.</p> <p>The only thing left to do is to wire up the custom ErrorHandlingControllerFactory in global.asax like this:</p> <div style="font-family: consolas; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: #2b91af">ControllerBuilder</span>.Current.SetControllerFactory(</p> <p style="margin: 0px">&nbsp;&nbsp;&nbsp; <span style="color: blue">new</span> <span style="color: #2b91af">ErrorHandlingControllerFactory</span>());</p></div> <p>Now any Controller action that throws an exception is gracefully handled by the injected IExceptionFilter. Since the filter is added as the last in the list of ExceptionFilters, any normal [HandleError] attribute and Controller.OnException override gets a chance to deal with the exception first, so this doesn't even change behavior of existing code.</p> <p>If you are trying this out on your own development machine, remember that you must modify your web.config like so:</p> <div style="font-family: consolas; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">customErrors</span><span style="color: blue"> </span><span style="color: red">mode</span><span style="color: blue">=</span>"<span style="color: blue">On</span>"<span style="color: blue"> /&gt;</span></p></div> <p>If you run in the RemoteOnly mode, you will still see the Yellow Screen of Death on your local box.</p><commit_msg>Formatted code in the same way as most other<commit_after>---
layout: post
tags: [ASP.NET MVC]
date: 2009-12-01 06:37:01 UTC
title: "Global Error Handling in ASP.NET MVC"
---
{% include JB/setup %}

<div id="post">
	<p>ASP.NET MVC comes with an error-handling feature that enables you to show nice error Views to your users instead of the dreaded Yellow Screen of Death. The most prominently described technique involves attributing either you Controller or a single Controller action, like we see in the AccountController created by the Visual Studio project template.</p><p><pre><div style="font-family: consolas; color: black; font-size: 10pt">[<span style="color: #2b91af">HandleError</span>]
<span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">AccountController</span> : <span style="color: #2b91af">Controller</span> { }</div></pre></p>
    <p>That sure is easy, but I don't like it for a number of reasons:</p> <ul> <li>Even though you can derive from HandleErrorAttribute, it's impossible to inject any dependencies into Attributes because they must be fully constructed at compile-time. That makes it really difficult to log errors to an interface.  <li>It violates the DRY principle. Although it can be applied at the Controller level, I still must remember to attribute all of my Controllers with the HandleErrorAttribute.</li></ul> <p>Another approach is to override Controller.OnException. That solves the DI problem, but not the DRY problem.</p> <p>Attentive readers may now point out that I can define a base Controller that implements the proper error handling, and require that all my Controllers derive from this base Controller, but that doesn't satisfy me:</p> <p>First of all, it still violates the DRY principle. Whether I have to remember to apply a [HandleError] attribute or derive from a : MyBaseController amounts to the same thing. I (and all my team members) have to remember this always. It's unnecessary project friction.</p> <p>The second thing that bugs me about this approach is that I really do <em>favor composition over inheritance</em>. Error handling is a <em>cross-cutting concern</em>, so why should all my Controllers have to derive from a base controller to enable this? That is absurd.</p> <p>Fortunately, ASP.NET MVC offers a third way.</p> <p>The key lies in the Controller base class and how it deals with IExceptionFilters (which HandleErrorAttribute implements). When a Controller action is invoked, this actually happens through an IActionInvoker. The default ControllerActionInvoker is responsible for gathering the list of IExceptionFilters, so the first thing we can do is to derive from that and override its GetFilters method:</p><p><pre><div style="font-family: consolas; color: black; font-size: 10pt"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">ErrorHandlingActionInvoker</span> :
&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">ControllerActionInvoker</span>
{
&nbsp;&nbsp;&nbsp; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IExceptionFilter</span> filter;
&nbsp;
&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> ErrorHandlingActionInvoker(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">IExceptionFilter</span> filter)
&nbsp;&nbsp;&nbsp; {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (filter == <span style="color: blue">null</span>)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"filter"</span>);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.filter = filter;
&nbsp;&nbsp;&nbsp; }
&nbsp;
&nbsp;&nbsp;&nbsp; <span style="color: blue">protected</span> <span style="color: blue">override</span> <span style="color: #2b91af">FilterInfo</span> GetFilters(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">ControllerContext</span> controllerContext,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">ActionDescriptor</span> actionDescriptor)
&nbsp;&nbsp;&nbsp; {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">var</span> filterInfo = 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">base</span>.GetFilters(controllerContext, 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; actionDescriptor);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; filterInfo.ExceptionFilters.Add(<span style="color: blue">this</span>.filter);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> filterInfo;
&nbsp;&nbsp;&nbsp; }
}</div></pre><p>
    <p>Here I'm simply injecting an IExceptionFilter instance into this class, so I'm not tightly binding it to any particular implementation  -  it will work with any IExceptionFilter we give it, so it simply serves the purpose of adding the filter at the right stage so that it can deal with otherwise unhandled exceptions. It's pure infrastructure code.</p> <p>Notice that I first invoke base.GetFilters and then add the injected filter to the returned list of filters. This allows the normal ASP.NET MVC IExceptionFilters to attempt to deal with the error first.</p> <p>This ErrorHandlingActionInvoker is only valuable if we can assign it to each and every Controller in the application. This can be done using a custom ControllerFactory:</p>
    <p><pre><div style="font-family: consolas; color: black; font-size: 10pt"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">ErrorHandlingControllerFactory</span> : 
&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">DefaultControllerFactory</span>
{
&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: #2b91af">IController</span> CreateController(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af">RequestContext</span> requestContext,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">string</span> controllerName)
&nbsp;&nbsp;&nbsp; {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">var</span> controller = 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">base</span>.CreateController(requestContext,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; controllerName);
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">var</span> c = controller <span style="color: blue">as</span> <span style="color: #2b91af">Controller</span>;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (c != <span style="color: blue">null</span>)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; c.ActionInvoker = 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">new</span> <span style="color: #2b91af">ErrorHandlingActionInvoker</span>(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">new</span> <span style="color: #2b91af">HandleErrorAttribute</span>());
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> controller;
&nbsp;&nbsp;&nbsp; }
}</div></pre></p>
    <p>Notice that I'm simply deriving from the DefaultControllerFactory and overriding the CreateController method to assign the ErrorHandlingActionInvoker to the created Controller.</p> <p>In this example, I have chosen to inject the HandleErrorAttribute into the ErrorHandlingActionInvoker instance. This seems weird, but it's the HandleErrorAttribute that implements the default error handling logic in ASP.NET MVC, and since it implements IExceptionFilter, it works like a charm.</p> <p>The only thing left to do is to wire up the custom ErrorHandlingControllerFactory in global.asax like this:</p>
    <p><pre><div style="font-family: consolas; color: black; font-size: 10pt"><span style="color: #2b91af">ControllerBuilder</span>.Current.SetControllerFactory(
&nbsp;&nbsp;&nbsp; <span style="color: blue">new</span> <span style="color: #2b91af">ErrorHandlingControllerFactory</span>());</div></pre></p>
    <p>Now any Controller action that throws an exception is gracefully handled by the injected IExceptionFilter. Since the filter is added as the last in the list of ExceptionFilters, any normal [HandleError] attribute and Controller.OnException override gets a chance to deal with the exception first, so this doesn't even change behavior of existing code.</p> <p>If you are trying this out on your own development machine, remember that you must modify your web.config like so:</p><p><pre><div style="font-family: consolas; color: black; font-size: 10pt"><span style="color: blue">&lt;</span><span style="color: #a31515">customErrors</span><span style="color: blue"> </span><span style="color: red">mode</span><span style="color: blue">=</span>"<span style="color: blue">On</span>"<span style="color: blue"> /&gt;</span></div></pre></p>
    <p>If you run in the RemoteOnly mode, you will still see the Yellow Screen of Death on your local box.</p>
{'fraction_non_alphanumeric': 0.17135007470959657, 'fraction_numerical': 0.011664337012580132, 'mean_word_length': 7.48936170212766, 'pattern_counts': {'":': 0, '<': 483, '<?xml version=': 0, '>': 483, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '251568', 'n_tokens_mistral': 6262, 'n_tokens_neox': 6043, 'n_words': 1977}