转载:http://blogs.microsoft.co.il/blogs/shay/archive/2009/03/06/real-world-error-hadnling-in-asp-net-mvc-rc2.aspx
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.
Posted: Mar 06 2009, 08:56 PM by שי יעקובי | with 9 comment(s)