Geeks With Blogs
C+++ on .NET while(x => x.CanLearnMore).Select( new { p.Info } )
| Home |

As ScottGu mentioned in his post, ASP.NET MVC supports error handling. But, as always, you need to take care of some (1) steps before it actually works completely.  In this post, I will show how to enable all the error handling, so that when an exception occurs in code, the user gets a nice screen.

You can start by creating a new ASP.NET MVC project.

Than open web.config and change the following item:

<configuration>
    <customErrors mode="On">
     
    </
customErrors>
</configuration>

Having this configuration will redirect all users to the default ‘~/views/shared/error.aspx’ when an exception is thrown in code.

The ‘Error.aspx’ view is a generic PageView and defined as this:

namespace MvcApplication1.Views.Shared
{
    public partial class Error : ViewPage<HandleErrorInfo>
    {
    }
}

Where HandlerErrorInfo is like this:

public class HandleErrorInfo
{
    public string ActionName { get; }
    public string ControllerName { get; }
    public Exception Exception { get; }
}

So in the view you can do things like:

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        Sorry, an error occurred while processing your request.
        Action = <%= ViewData.Model.ActionName %>
        Controller = <%= ViewData.Model.ControllerName %>
        Message = <%= ViewData.Model.Exception.Message %>
        
    </h2>
</asp:Content>

 

A short and simple post, but as it is my first, it’s a start :).

Posted on Thursday, January 8, 2009 12:45 PM | Back to top


Comments on this post: ASP.NET MVC Beta 1 – Error handler example

# re: ASP.NET MVC Beta 1 – Error handler example
Requesting Gravatar...
Good post, sorry to see it was the only one :-)
Left by Adrian Grigore on Jan 26, 2010 11:16 AM

# re: ASP.NET MVC Beta 1 – Error handler example
Requesting Gravatar...
Thanks for this, the mark-up in this view is now removed from the MVC 2.0 Visual Studio project and useful for my reference.

For security against XSS though, you should always use Html.Encode(ViewData.Model.Exception.Message) or <%: =ViewData.Model.Exception.Message %> if using .NET 4. This is especially important when writing out an exception.
Left by DalSoft on May 06, 2010 5:29 AM

# re: ASP.NET MVC Beta 1 – Error handler example
Requesting Gravatar...
WElcome.I am looking forward for your next post on this topic.Your posts really do the help.Thank you! http://www.highsneakers.com/ kids shox running shoesso cute!
Left by good product on Jun 11, 2010 2:57 AM

# re: ASP.NET MVC Beta 1 – Error handler example
Requesting Gravatar...
try it
Left by ding on Jul 30, 2010 3:12 AM

Your comment:
 (will show your gravatar)


Copyright © C+++ | Powered by: GeeksWithBlogs.net