Friday, December 5, 2014

Exception Handling in asp.net mvc using global.asax application_error() Method

hi now lets see how to catch exception in asp.net mvc using global.asax application_error() Method.

1. set Custom Error to Off in the web.config file
2. go to global.asax file and add this below code.
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
string action;
switch (httpException.GetHttpCode())
{
case 404:
// page not found
action = “HttpError404″; // create action method named HttpError404  in controller and also add the appropriate view
break;
case 500:
// server error
action = “HttpError500″; // create action method named HttpError500 in controller and also add the appropriate view
break;
default:
action = “HttpOtherErrors”; // create action method named HttpOtherErrors in controller and also add the appropriate view
break;
}
// clear error on server
Server.ClearError();
Response.Redirect(String.Format(“~/ErrorHandle/{0}/?message={1}”, action, exception.Message)); // ErrorHandle is the controller Name 
}
else
{
Response.Redirect(String.Format(“~/ErrorHandle/{0}/?message={1}”, “HttpOtherErrors”, exception.Message));
}
}
3. in controller catch the exception message and show it in the view
public ActionResult HttpOtherErrors(string message)
{
ViewBag.ExceptionMessg = message;
return View();
}

No comments:

Post a Comment