获取查询/ CommandText中导致抛出SQLException [英] Obtain the Query/CommandText that caused a SQLException

查看:78
本文介绍了获取查询/ CommandText中导致抛出SQLException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于获取查询/ CommandText中导致抛出SQLException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆