I want to call the JavaScript function (which internally shows a popup about the error message) from global.asax.cs file. Here is my code that I am trying in Global.asax.cs file,
protected void Application_Error(object sender, EventArgs e)
{
System.Web.UI.Page mypage = (System.Web.UI.Page)HttpContext.Current.Handler;
mypage.RegisterStartupScript("alert", "<script language=javascript>alert('test');</script>");
}
But it is not calling the alert nor giving any error or warning message in Firebug and the Google Chrome console. How can JavaScript code be called?
There are two different kind of errors that you get at that point.
The compiler can throw any error there, for example, it can not find a literal control in the code behind. In this case your page does not even exist and there is no way to get it at that point and give this JavaScript alert.
Errors by the run time of your program, for example, a null exception, can also stop the page from rendered and this is also stop the page and you can not have the page handler there.
So the HttpContext.Current.Handler is NOT a page
.
In general, the Application_Error is used for capture and log unhandled errors
, to solve them later, and maybe show a better error page to the user.
If you try just to see your error on debug, you can use code like:
void Application_Error(object sender, EventArgs e)
{
Exception LastOneError = Server.GetLastError();
if (LastOneError != null)
{
Debug.Fail("Unhandled error: " + LastOneError.ToString());
LogTheError(LastOneError);
}
}
The only way that I can think to make something similar is to make a redirect when the error appears to a new page that explain the error - but this is what the custom error page already do.
This is the way I handle my custom errors and stay on the same page. The file check is to avoid possible close loop that can crash the pool.
string cTheFile = HttpContext.Current.Request.Path;
if (!cTheFile.EndsWith("ErrorHandlePage.aspx"))
Server.Transfer("~/ErrorHandlePage.aspx");