When an error occurs in your ASP.NET application you are given a nice browser yellow screen of death. To fix this ASP.NET provides a method to redirect to a common page with user friendly message.
This can be achieved using ASP.NET MVC2.0 by the following steps.
1. Include the following in the web.config under System.Web tag
< customErrors mode="On" redirectMode="ResponseRedirect" defaultRedirect="~/Sample/ErrorPage" >
< error statusCode="404" redirect="~/Sample/PageNotFound"/>
< /customErrors >
This helps to dedirect a default page. Here for the 404 errors the page is redirected to PageNotFound and for any unhandled status code errors the page is redirected to ResponseRedirect.
Here the page redirect syntax is Controller/Action
2. To retrieve the stack trace error message, use Application_Error method in Global.ascx
The following code snipet helps to retrive the stack trace message and finally redirect to a error page with user friendly error message.
protected void Application_Error(object sender, EventArgs e)
{
HttpContext ctx = System.Web.HttpContext.Current;
Exception exception = ctx.Server.GetLastError();
Response.Clear();
Context.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Sample";
routeData.Values["action"] = "ErrorPage";
routeData.Values["ex"] = exception;
Object obj = new object();
if (exception != null)
{
string exMsg = "User: '" + User.Identity.Name + "' DateTime: '" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + "'" + Environment.NewLine +
"Source: " + exception.Source + Environment.NewLine +
"Message: " + exception.Message + Environment.NewLine +
"Inner Exception: " + exception.InnerException + Environment.NewLine +
"Stack trace: " + exception.StackTrace;
WriteToLogFile(exMsg);
}
IController sample = new SampleController();
sample.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
When "Application_Error" method is used, the custom redirect page specified in the WebConfig doesnt work. We need to give redirect from the "Application_Error" method by creating an object of controller and calling the specific ActionResult.
No comments:
Post a Comment