Home > DeveloperSection > Forums > How to HandlError in mvc?
Goti Bandu

Total Post:119

Points:835
Posted on    October-29-2014 11:27 PM

 ASP.NET MVC ASP.NET MVC  Mvc4 
Ratings:


 1 Reply(s)
 604  View(s)
Rate this:
How do I go about the [HandleError] filter in asp.net MVC Preview 5?
I set the customErrors in my Web.config file

<customErrors mode="On" defaultRedirect="Error.aspx">

  <error statusCode="403" redirect="NoAccess.htm"/>

  <error statusCode="404" redirect="FileNotFound.htm"/>

</customErrors>

and put [HandleError] above my Controller Class like this:

[HandleError]

        public class DSWebsiteController : Controller

        {

            [snip]

            public ActionResult CrashTest()

            {

                throw new Exception("Oh Noes!");

            }

        }

Then I let my controllers inherit from this class and call CrashTest() on them. Visual studio halts at the error and after pressing f5 to continue, I get rerouted to Error.aspx?aspxerrorpath=/sxi.mvc/CrashTest (where sxi is the name of the used controller. Off course the path cannot be found and I get "Server Error in '/' Application." 404.



Barbara Jones

Total Post:13

Points:91
Posted on    October-29-2014 11:30 PM

[HandleError]

When you provide only the HandleError attribute to your class (or to your action method for that matter), then when an unhandled exception occurs MVC will look for a corresponding View named "Error" first in the Controller's View folder. If it can't find it there then it will proceed to look in the Shared View folder (which should have an Error.aspx file in it by default)

[HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")]]

[HandleError(ExceptionType = typeof(NullReferenceException), View = "LameErrorHandling")]]

You can also stack up additional attributes with specific information about the type of exception you are looking for. At that point, you can direct the Error to a specific view other than the default "Error" view.


Don't want to miss updates? Please click the below button!

Follow MindStick