1

I have a .NET web application that frequently executes queries to get data from a local database.

In situations where the query doesn't run (due to an exception) or the query returns an unexpected set of data (such as an empty set). I want to be able to rebuild the query (replacing it's @parameters with the values actually used) and store the complete query in the database along with the exception.

I'm aware that I can do this through standard code but I was wondering whether it would be safer to do via Elmah?

Also would doing this via Elmah give me the ability to be able to view the executed sql through elmah.axd (when access is enabled)?

Brokenlynx
  • 43
  • 1
  • 6

2 Answers2

0

Unless the thrown exception includes the query with the actual values, ELMAH doesn't help you there other than logging the exception. You can catch the exception yourself and do a custom logging to ELMAH using the ErrorSignal.Raise method as explained here: How to use ELMAH to manually log errors?

Community
  • 1
  • 1
ThomasArdal
  • 4,999
  • 4
  • 33
  • 73
0

I log SQL exceptions by passing the exception and the actual command to a new Exception class. The class wraps the SqlException and the System.Data.Common.DbCommand objects. Using that information I can create a message to provide the sql command details:

 public override string Message
    {
        get
        {
            StringBuilder message = new StringBuilder("");
            StringBuilder sql = new StringBuilder("");
            sql.AppendFormat(" {0} ", Command.CommandText);
            foreach (SqlParameter param in Command.Parameters)
            {
              sql.AppendFormat(" {0} - {1}", param.ParameterName,
                                 param.Value.ToString());
            }
            message.AppendFormat("Error: {0} SQL: {1}  User: {2}", SqlEx.Message, 
                                  sql, Username);
            return message.ToString();
        }

    }

Finally, I use the ErrorSignal Raise method to log the message in Elmah:

Elmah.ErrorSignal.FromCurrentContext().Raise(new DetailSqlException(e.Exception as SqlException, e.Command, user));
cdev
  • 166
  • 5