我有一个记录器,用于记录内部应用程序的异常信息。
当我们记录SQL异常时,如果我们可以看到导致异常的实际查询,那将非常有用。
我们有办法实现这一目标吗?
using (var command = new SqlCommand(connection, "dbo.MyProc"))
{
try
{
command.Execute();
}
catch (DbException ex)
{
throw new InvalidOperationException(ex.Message + " - " + command.Text, ex);
}
}
通过这种方式,您可以记录这个更具表现力的异常。
protected virtual TResult ExecuteAndLogError<TResult>(Func<TResult> 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;
}
}
在我的SQL代码中,我从数据层帮助程序方法调用ExecuteAndLogError。所有数据层方法都调用ExecuteAndLogError,因此只有一段代码可以记录SQL错误。
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;
}
您可以像这样使用它:repo.ExecuteDataTable("SELECT * FROM Users");
如果存在异常,则可以实现LogError方法来执行其他日志记录。其中一些代码摘自Subtext Blog数据层类。