是否可以使用 SqlException.LineNumber 来识别异常是否与连接相关?
我查看了瞬态故障处理框架代码试图解决暂时失去与 SQL Server 的连接。这里有一个关键点:当出现与 SQL 相关的问题(如语法错误)和与 SQL 无关的问题(如无连接)时,都会抛出 SqlException
。
当然,我只需要尝试从后一类问题中恢复 - 如果我的代码运行格式错误的查询,我需要快速失败,而不是重试任何内容。
该框架尝试通过检查 SqlError.Number 并将其与大量硬编码值进行比较来区分这些类。一旦 SQL Server 内部发生变化,基于此策略的大量知识和代码肯定需要维护。
我想也许我可以使用 SqlException .LineNumber
代替?根据 MSDN,行号从 1 开始,行号 0 意味着行号不适用,所以我猜这意味着问题与 SQL 无关。我尝试了一段时间 - 每当我遇到连接问题时,LineNumber
始终为零。
使用 SqlException.LineNumber
是识别异常是由于 SQL 查询问题还是由于连接问题引起的可靠方法吗?
I looked though Transient Fault Handling Framework code trying to address temporary loss of connectivity to SQL Server. There's one key point there: SqlException
is thrown both when there's an SQL-related problem (like syntax error) and something not related to SQL (like no connection).
Of course I need to try recover from the latter class problems only - if my code runs a malformed query I need to fail fast, not retry anything.
The framework tries to distinguish between those classes by examining SqlError.Number
and comparing it against a huge set of hardcoded values. That's lot of knowledge and code based on this strategy will definitely need maintenance once SQL Server internals change.
I thought maybe I can use SqlException.LineNumber
instead? According to MSDN, line numbering starts at 1 and line number 0 means the line number is not applicable so I guess that means the problem is not SQL related. I tried this for a while - whenever I have connectivity problems LineNumber
is always zero.
Is using SqlException.LineNumber
a good reliable way for identifying whether an exception is due to an SQL query problem or due to connectivity problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不相信您可以可靠地使用 LineNumber 属性作为异常是与连接相关的错误的指示符。当存储过程、触发器或函数期间发生错误时,将设置 LineNumber。但是,在这些项目之外的查询中,甚至在可能导致 LineNumber 为 0 的 SqlException 的视图中,您仍然可能会遇到错误。最好的方法是使用您所描述的技术,使用 Number 属性与硬编码值集进行比较。
I don't believe you can reliably use the LineNumber property as indicator that an exception is a connection-related error. The LineNumber will be set when an error occurs during a Stored Procedure, Trigger, or Function. But, you could still have errors in queries outside of those items or even in views that could cause an SqlException with a LineNumber of 0. The best approach is to use the technique you described using the Number property compared to the set of hardcoded values.