DCSIMG
Real world error hadnling in ASP.NET MVC RC2. - new { Name = ”Shay Jacoby” }

new { Name = ”Shay Jacoby” }

Maximum separation, minimum Dependencies, No Injections.

Real world error hadnling in ASP.NET MVC RC2.

I would like to share with You my ASP.NET MVC Error Handling solution after reading this question in stackoverflow.com 

Goal:

To catch every error that occures on server include HttpExeptions like 404 (Page not found).

The ability to choose a specific View (error Template) for some errors and a generic View/Behaviour if nor specific has been specified.
Scenario 1:
anonymus user typed a wrong url.
Actions:
display a user friendly message like: "OOPS, The page is missing... back to home"
Log the error to .log file on server.
Send email to admin.

Senario 2:
same as scenario 1 but one difference : user is anonymus but his IP is from our company office.
Actions:
show the detailed error.

Let's see some code:

 

Add this method to Global.asax:

protected void Application_Error(object sender, EventArgs e)
{
 
   Exception exception = Server.GetLastError();
 
 // Log the exception.
 ILogger logger = Container.Resolve<ILogger>();
 logger.Error(exception);
 
 Response.Clear();
 
 
 HttpException httpException = exception as HttpException;
 RouteData routeData = new RouteData();
 routeData.Values.Add("controller", "Error");
 
 if (httpException == null)
 {
      routeData.Values.Add("action", "Index");
 }
 else //It's an Http Exception, Let's handle it.
 {
 
  switch (httpException.GetHttpCode())
  {
    case 404:
      // Page not found.
      routeData.Values.Add("action", "HttpError404");
      break;
     case 500:
     // Server error.
       routeData.Values.Add("action", "HttpError500");
       break;
       // Here you can handle Views to other error codes.
        // I choose a General error template  
        default:
        routeData.Values.Add("action", "General");
        break;
     }
  }
 
 // Pass exception details to the target error View.
 routeData.Values.Add("error", exception);
 
 // Clear the error on server.
 Server.ClearError();
 
// Call target Controller and pass the routeData.
 IController errorController = new ErrorController();
 errorController.Execute(new RequestContext(
new HttpContextWrapper(Context), routeData));
 
}


Created a new controller called ErrorController:
You can specify some more behaviors to another eception types, I breated a view just for error: 404, 500.

 

    public ActionResult HttpError404(string error)
        {
            ViewData["Title"] = "Sorry, an error occurred while processing your request. (404)";
            ViewData["Description"] = error;
            return View("Index");
        }
 
        public ActionResult HttpError500(string error)
        {
            ViewData["Title"] = "Sorry, an error occurred while processing your request. (500)";
            ViewData["Description"] = error;
            return View("Index");
        }
 
 
        public ActionResult General(string error)
        {
            ViewData["Title"] = "Sorry, an error occurred while processing your request.";
            ViewData["Description"] = error;
            return View("Index");
        }

 

I attached an example project to this post.

 

תוכן התגובה

ASP.NET MVC Archived Blog Posts, Page 1 כתב/ה:

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

# March 7, 2009 1:54 AM

Real world error hadnling in ASP.NET MVC RC2. - new { Name = ???Shay … כתב/ה:

Pingback from  Real world error hadnling in ASP.NET MVC RC2. - new { Name = ???Shay &#8230;

# March 7, 2009 7:53 AM

geff zhang כתב/ה:

应用程序发生异常时,给用户一个友好的处理方式,同时将异常记录下来并通知系统管理员或是运维人员是应用的开发的常用场景。web form上微软提供了一个工具包,关于这个工具包参看推荐一个工具包自定义HTT

# March 14, 2009 6:21 AM

Mose כתב/ה:

2 remarks :

1) the HandleError attribute is of no use anymore (in Home & Error controller) as you are using a custom error handling.

2) in your sample the Application_Error method is called twice (breakpoint told me so).

Whatever : good sample.

# April 2, 2009 11:28 AM

Patrick כתב/ה:

It looks like this works only on GET requests. If I have an exception which is caused after an POST then this ain't working.

There seems to be an innerexception in the Context, "This operation requires IIS integrated pipeline mode."

Has somebody else noticed this also?

# April 8, 2009 1:53 PM

flyfesh כתב/ה:

应用程序发生异常时,给用户一个友好的处理方式,同时将异常记录下来并通知系统管理员或是运维人员是应用的开发的常用场景。web form上微软提供了一个工具包,关于这个工具包参看推荐一个工具包自定义HTTP 404错误。如何在asp.net mvc上实现这样的功能呢?asp.net mvc 在创建项目的时候在Views的Shared目录下有一个错误处理页Error.aspx视图,这个默认的错误处理功能没有实现对错误日志的记录。

# June 3, 2009 6:03 AM

Eduardo כתב/ה:

Do you know why if the error is a security error (try posting <script> in a textbox) it is not catched?

# July 16, 2009 1:56 AM

Andrew כתב/ה:

Thanks for the code.  However it appears to break if I type in a URL for example "/foo/foo/foo/foo"

"The SessionStateTempDataProvider requires SessionState to be enabled."

# July 23, 2009 12:51 PM

Sam Shawn כתב/ה:

Thanks your codes, but InvalidOperationException with message "Session state disabled" at

 errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

# October 15, 2009 5:28 PM

Palantir כתב/ה:

Great code. You have a typo in the page title, though :)

# October 23, 2009 11:17 AM

Nimesh כתב/ה:

i am getting errror:

The SessionStateTempDataProvider requires SessionState to be enabled.

# October 23, 2009 12:34 PM

joedirt כתב/ה:

I've tried to implement this into my project and I get a blank screen back.  The response is empty and the URL doesn't change to my error view.  I've stepped through the code in the debugger and I see the HttpError404 controller method being called and returning the View, but then I don't get anything on the screen.  Any suggestions?

# December 7, 2009 5:12 PM

שי יעקובי כתב/ה:

Please check with the debugger

# December 9, 2009 9:15 PM

Scott Findlater כתב/ה:

i am also getting the error:

The SessionStateTempDataProvider requires SessionState to be enabled.

Any ideas?

# January 2, 2010 4:48 PM

Jared כתב/ה:

From what I see, and I could be wrong, the 'SessionStateTempDataProvider requires SessionState' error is caused from a resource request such as an image or file. No session state is provided with such requests, therefor the SessionState is null. To handle this, I do this:

try

           {

               IController errorController = new ClientPortal.Controllers.ErrorController();

               errorController.Execute( new RequestContext(

                    new HttpContextWrapper( Context ), routeData ) );

           }

           catch ( Exception ex )

           {

               //Do Nothing... 9 times out of 10 it's a missing resouce that doesn't contain state

           }

Hope this helps... please post if I am wrong.

# February 12, 2010 7:43 PM

Sam Delaney כתב/ה:

I've run the sample project, with a network analyser running, and at no point do we get a 404 or 500 response code back, just 200s.

# April 15, 2010 6:32 PM

ASP.NET MVC| [MVC]Real world error hadnling in ASP.NET MVC RC2. | Mikel כתב/ה:

Pingback from  ASP.NET MVC|  [MVC]Real world error hadnling in ASP.NET MVC RC2. | Mikel

# May 6, 2010 11:04 AM

Matt Kocaj כתב/ה:

@Jared:

That fix of swallowing the exception does not work even with the "/foo/foo/foo/foo" example. I suspect that the Session State is required a little more than 10% of the time.

# May 16, 2010 8:50 AM

How to handle 404 errors in MVC 3 | | Yasser ShaikhYasser Shaikh כתב/ה:

Pingback from  How to handle 404 errors in MVC 3 |  | Yasser ShaikhYasser Shaikh

# July 31, 2012 7:23 PM

How can I properly handle 404 in ASP.NET MVC? | Everyday I'm coding כתב/ה:

Pingback from  How can I properly handle 404 in ASP.NET MVC? | Everyday I&#039;m coding

# March 12, 2013 5:31 AM
שלח תגובה

(שדה חובה)  

(שדה חובה)  

(אופציונלי)

(שדה חובה) 

Please add 7 and 7 and type the answer here:


Enter the numbers above: