开发者

How to handle ASP.NET application error that occurs on application start and transfer & display error in MVC view?

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 applicat开发者_运维知识库ion 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.


The reason why Request and Response objects are null inside your Application_Error event is because the Application_Start event is not associated with any user, therefore you cannot redirect from it. Only the Application and Server built-in objects are available. Referencing the Session, Request, or Response objects would cause an error.

One workaround is to use try/catch and in the catch block log the error and set some global variable which indicates that something went wrong during application startup. Later on Application_BeginRequest you could check this variable and redirect accordingly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜