Application_Error disparando incluso para excepciones manejadas

I have some code to display a button if a URL exists:

try
{
    string dashboardURL = Config.RootUrl + "/Dashboard/Default.aspx";
    WebRequest req = WebRequest.Create(dashboardURL);
    WebResponse response = req.GetResponse();
    btnDashboard.Visible = true;
}
catch (Exception)
{
    btnDashboard.Visible = false;
}

However, when debugging, req.getResponse() causas Application_Error to fire. I checked the exception being caught here and it is a System.Net.WebException. My understanding was that Application_Error is fired for unhandled exceptions.

If I change the code to force an exception as follows:

try
{
    string dashboardURL = Config.RootUrl + "/Dashboard/Default.aspx";
    WebRequest req = WebRequest.Create(dashboardURL);

    int j = 0;
    int i = 1 / j;

    WebResponse response = req.GetResponse();
    btnDashboard.Visible = true;
}
catch (Exception)
{
    btnDashboard.Visible = false;
}

luego Application_Error is not fired, which is good. Is there something particular about handling errors with GetResponse() that always causes Application_Error to fire, even if the exception is handled?

preguntado el 04 de julio de 12 a las 10:07

are you sure above exception is caught? -

As the name implies 'Application Error' is an error issued at the application level. -

Is Config.RootUrl + "/Dashboard/Default.aspx" in the same server/application? -

2 Respuestas

In Application_Error check the exception:

var exception = Server.GetLastError();

It is impossible that Application_Error is fired with this code. Your exception must be after this try/catch Block.

Also try to Clean and Rebuild your solution, or force the Designer File to get recreated (Change something on aspx file).

I tested your code on different ASP.NET Version, even on MVC3/MVC4 Environment and Application_Error is never fired!

Respondido 11 Jul 12, 04:07

Es el /Dashboard/Default.aspx in the same server/application?

If so then processing of that request can cause an error that will be captured by the Application_Error. The reason is that by doing GetResponse() you are doing a HTTP request, and any exceptions that happen while processing the request on (potentially) remote server will not be handled by try/catch on the calling code. In your special case remote server = local server, but the idea does not change.

Respondido 12 Jul 12, 23:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.