Custom Error Handling using Application_Error() in MVC3 and MVC4 application

1757
Views
1
Answers

How do I handle errors in my MVC 3/ 4 application. Should I have the handling code in Global.asax Application_Error() or should redirect to a controller action?

edit | flag
Sam Bells
Asked on: Feb 21, 2012 at 2:33AM

1 Answers

132
1
132

You should basically handle all your application errors in the global.asax without the need for an error controller, decorating with the [HandlerError] attribute.

If you need to redirect to some controller actioon you can do so by implementing the code below

protected void Application_Error(object sender, EventArgs e) {
 
Exception exception = Server.GetLastError();
 
Response.Clear();

 
HttpException httpException = exception as HttpException;

 
if (httpException != null) {
   
string action; // action in Error controller

   
switch (httpException.GetHttpCode()) {
     
case 404:
       
// page not found
        action
= "Error404";
       
break;
     
case 500:
       
// server error
        action
= "Error500";
       
break;
     
default:
        action
= "General";
       
break;
     
}

     
// clear error on server
     
Server.ClearError();

     
Response.Redirect(String.Format("~/Error/{0}/?errormessage={1}", action, exception.Message));
   
}

Your controller code

    // GET: /Error/Error404
   
public ActionResult Error404(string errormessage)
 
{
       
return View("ErrorspecificView", errormessage);
   
}
edit | flag
Gokul A
Answered on: Feb 21, 2012 at 2:41AM

Post your Answer

Search

Welcome to Ask Amoeba!
This is 100% free and interactive site for sharing professional Questions and Answers, Opensource projects, Interview questions.
Learners, beginners, Experts stop and share your knowledge and ideas!

Browse Categories

Browse Tags