locked
Error handling help RRS feed

  • Question

  • User761356933 posted

    Hello,

    I have several database function in a class. However I am wondering how I can go about error handling. Currently nothing happens, for example my dropdown failed to populate and was blank but no errors were displayed. Upon debugging there was an issue with a passed sql parameter. what would you suggest I do here in the catch statement?

    also you can see that my function is expecting an array of parameters, how would I go about using this function when no parameters are required?

    public DataTable executeSelectQuery(string _query, SqlParameter[] _Parameters)
    {
    SqlCommand myCommand = new SqlCommand();
    DataTable dt = new DataTable();
    dt = null;
    DataSet ds = new DataSet();
    try
    {
    myCommand.Connection=openConnection();
    myCommand.CommandText=_query;
    myCommand.Parameters.AddRange(_Parameters);
    myAdapter.SelectCommand = myCommand;
    myCommand.ExecuteNonQuery();
    myAdapter.Fill(ds);
    dt = ds.Tables[0];

    }
    catch (SqlException e)
    {// send email to admin? catch at UI to display error message to user

    return null;
    }

    finally
    {//close connection
    conn.Close();
    }

    return dt;

    }

    Tuesday, July 3, 2018 10:30 AM

Answers

  • User475983607 posted

    Of course no errors are displayed, the catch block returns null. 

    Upon debugging there was an issue with a passed sql parameter. what would you suggest I do here in the catch statement?

    Either remove the try/catch or properly handle the error in the catch block.  The common approach is to come up with an exception handling design.  For example, logging unexpected errors in a database, event viewer, or file.  During developing you want to see the exceptions while production logs errors and displays a friendly error page.  Anyway, this subject is rather mature.  Start with the following.

    https://docs.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/aspnet-error-handling

    also you can see that my function is expecting an array of parameters, how would I go about using this function when no parameters are required?

    Validate the input parameters which is a common and recommend practice.

    public DataTable executeSelectQuery(string _query, SqlParameter[] _Parameters)
    {
      if(_Parameters.Count() == 0)
      {
         throw new ArgumentException("Parameters cannot be empty");
      }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 3, 2018 10:46 AM