Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling in ASP.NET Webforms

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)

like image 945
juan Avatar asked Feb 17 '09 19:02

juan


1 Answers

  • 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>
  • Useful links

    MSDN

    MSDN

    Exception Logging- Peter Bromberg

like image 67
PRR Avatar answered Sep 26 '22 00:09

PRR