NickG
NickG

Reputation: 9812

How can I catch *all* exceptions in Application_BeginRequest?

I'm trying to catch a specific exception which is occurring in my Application_BeginRequest.

So far I've been totally unable to catch the exception to see what's going wrong, but the user sees a 500 Internal Server Error. All other exceptions are logged with Elmah but in this instance, Elmah is not logging it.

try
    {
        if (!String.IsNullOrEmpty(Request.ServerVariables["HTTP_X_BLUECOAT_VIA"]))
        {
            string original = Request.QueryString.ToString();
            HttpContext.Current.RewritePath(Request.Path + "?" + original.Replace(Server.UrlEncode("amp;"), "&"));
        }
    }
    catch (Exception ex) { 
    }

If I change catch to catch(Exception ex) the exception is NOT caught and the error still occurs.

If I comment out the code inside the try block, the page loads fine with no errors, so the error is definitely occurring within the try block, but somehow throwing an exception which cannot be caught using a try/catch block.

Upvotes: 0

Views: 587

Answers (1)

Babak Naffas
Babak Naffas

Reputation: 12561

Try Exception exception = Server.GetLastError(); in the body of your catch block if other attempts aren't working.

You can also handle uncaught exceptions using the Application_Error event in the same Globals class.

 protected void Application_Error(object sender, EventArgs e){
      Exception exception = Server.GetLastError(); 
 }

Upvotes: 1

Related Questions