views:

767

answers:

5

What is the preferred method for handling exceptions in ASP.NET Webforms?

You have the Page_Error method that you add (I think) at web.config level, and the entire site gets redirected there when an error occurs.

Does that mean you shouldn't use try-catch anywhere in a webforms application? (Assuming you don't want to hide any errors)

+8  A: 

Only catch the errors you can handle. If you can handle them in a manner that allows the page to continue loading then do so. Any other exception that would wreck the page should not be handled in any control or page as you would not be able to do anything anyways. Let it go to the global.asax handler and make sure you log the exception.

Andrew Hare
A: 

You should use try/catch in places where you can do something meaningful with error, like fixing it or taking a different approach.

For all other cases you should use global try/catch using web.config custom errors page or Application_Error event to log the error and possibly to show it to the user.

Alex Reitbort
+3  A: 

In addition to Andrew's suggestion, make sure to update the web.config file to set CustomErrors to "On" and specify a generic error page to redirect these top level errors. Global_asax will still log the error, and then the user can see a friendly page. It will also allow you to configure a few of the standard type errors, such as 404s and 200s, plus much more.

Dillie-O
A: 

If you use validation controls or check and validate user input in your code behind that will go a long way to preventing errors. I do recommend having a generic error page that can log the error for you. In cases where you are unsure of what will happen i suggest catching the error and handling it if at all possible and work on finding a way to know that what you are going to run will work before doing it.

Do you have a specific example in mind of where you might expect to encounter an error of this sort. One that I know of is when a session expires and you can no longer process the page. I check for this on every page load before anything else is run and then redirect the user if this has occurred.

Middletone
A: 
  • Web Application will normally consists of UI, Business and Data access layer.Each layer must do its part regarding exception handling. Each layer must (for code re usability) check for error condition and wrap exception(after logging it) and maybe propagated to the calling layer. The UI layer should hide exception and display a friendly message. Catching all exception in UI maybe not a good idea. Exceptions if possible should be logged in Database. This will allow ease of maintainence and correction of bugs

  • Avoid catching exceptions as far as possible. Try and validate all inputs before you use them. Rigorously validation( both client and server side) inputs with help of validation controls, custom controls and regular expression is a must.

    string fname = "abc";
    //Always check for condition, like file exists etc...
    if (System.IO.File.Exists(fname))
    {
    
    
    }
    else
    {
    
    
    }
    
  • Always make sure clean up code is called. Using statement or try finally.

  • You can catch all exceptions in Global.asax (asp.net application file)

    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs
        Exception objErr = Server.GetLastError().GetBaseException();
        string err = "Error Caught in Application_Error event\n" +
           "Error in: " + Request.Url.ToString() +
           "\nError Message:" + objErr.Message.ToString()+ 
           "\nStack Trace:" + objErr.StackTrace.ToString();
        EventLog.WriteEntry("Sample_WebApp",err,EventLogEntryType.Error);
        Server.ClearError();
        //additional actions...
    
    
    }
    

and add <customerror> section in your web config to redirect user to a separate page

    <customErrors defaultRedirect="error.htm" mode="On">
    </customErrors>
PRR