获取查询/ CommandText中导致抛出SQLException抛出、CommandText、SQLException

由网友(泪水雨水相混)分享简介:我有一个记录器,在内部应用程序记录异常的信息为我们的。I've got a logger that records exception information for our in house applications.当我们登录SQL异常这将会是超级有用的,如果我们可以看到,导致异常的实际查询。When we...

我有一个记录器,在内部应用程序记录异常的信息为我们的。

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

当我们登录SQL异常这将会是超级有用的,如果我们可以看到,导致异常的实际查询。

When we log SQL exceptions it'd be super useful if we could see the actual query that caused the exception.

有没有一种方法,我们可以做到这一点?

Is there a way we can achieve this?

推荐答案

SQLEXCEPTION 不持有引用的SqlCommand 导致异常。在你的记录是没有办法做到这一点。你可以做的就是赶上执行的SqlCommand 的SQLException的方法,敷在一个更具描述性的异常。例如:

The SqlException does not hold a reference to the SqlCommand that caused the exception. In your logger there is no way to do this. What you could do is catch the SqlException in the method that executes the SqlCommand and wrap it in a more descriptive exception. Example:

using (var command = new SqlCommand(connection, "dbo.MyProc"))
{
    try
    {
        command.Execute();
    }
    catch (DbException ex)
    {
        throw new InvalidOperationException(ex.Message + " - " + command.Text, ex);
    }
}

这样,您就可以登录这更EX pressive例外。

This way you can log this more expressive exception.

阅读全文

相关推荐

最新文章