I know that ASP.NET MVC has error filter attribute to handle specified error type. However, this feature cannot catch any error that occurs when application start. Therefore, I need to add some code to “Application_Error” method for handling this error like the following code.
public void Application_Error(object sender, EventArgs e)
{
// At this point we have information about the error
var ctx = HttpContext.Current;
var exception = ctx.Server.GetLastError();
var errorInfo =
"<br>Offending URL: " + ctx.Request.Url +
"<br>Source: " + exception.Source +
"<br>Message: " + exception.Message +
"<br>Stack trace: " + exception.StackTrace;
ctx.Response.Write(errorInfo);
Server.ClearError();
}
Although, this code will works fine, when normal application error occurs like error that occurs in view page. Nevertheless, it does not work when error occurs on application starting because request and response objects are always null.
Next, I try to solve this question by setting default redirect in custom errors like the following code.
<customErrors mode="On" defaultRedirect="Scripts/ApplicationError.htm"></customErrors>
Unfortunately, it does not work because when application receive redirected request, it try to start application again and it throw exception again.
How do to solve this problem? Alternatively, Do you have other idea for handling this error.
Thanks,
PS. The main reason for creating this handler because I want to display error when application cannot connect to other service like database for caching data on application start.