Obtain the Query/CommandText that caused a SQLException

前端 未结 3 793
北荒
北荒 2020-12-06 16:40

I\'ve got a logger that records exception information for our in house applications.

When we log SQL exceptions it\'d be super useful if we could see the actual quer

3条回答
  •  爱一瞬间的悲伤
    2020-12-06 17:27

    The DRYest way to do this is to write a helper method that takes a delegate, the sql command text, and optionally a sql parameter array if you're using parameterized queries. Wrap the delegate in a try catch block and call the LogError method when there is an exception:

    protected virtual TResult ExecuteAndLogError(Func code, string sql, SqlParameterCollection parameters = null)
    {
        try {
            if ((System.Diagnostics.Debugger.IsAttached))
                PrintSqlToDebug(sql, parameters);
            return code();
        } catch (Exception ex) {
            LogError(sql, parameters, ex);
            throw;
        }
    } 
    

    In my SQL code I call ExecuteAndLogError from data layer helper methods. All of the data layer methods call ExecuteAndLogError, so there is only one section of code to log SQL errors.

    public virtual DataTable ExecuteDataTable(SqlCommand command, params SqlParameter[] parameters)
    {
        command.Parameters.AddRange(parameters);
        DataTable table = new DataTable();
    
        using (SqlDataAdapter adapter = new SqlDataAdapter(command)) {
            using (command) {
                ExecuteAndLogError(() => adapter.Fill(table), command.CommandText, command.Parameters);
            }
        }
    
        return table;
    

    }

    You can use it like this: repo.ExecuteDataTable("SELECT * FROM Users"); If there is an exception you can implement the LogError method to perform additional logging.

    Some of this code was taken from the Subtext Blog data layer classes.

提交回复
热议问题