简体   繁体   English

从 .NET 中的 SQL 服务器捕获 RAISERROR

[英]Catch RAISERROR from SQL Server in .NET

I have a stored procedure in SQL Server that throws an error whenever a condition is hit.我在 SQL 服务器中有一个存储过程,只要遇到条件就会引发错误。 In order to catch this error and display it to the user, I use为了捕获此错误并将其显示给用户,我使用

try 
{
   //code
} 
catch (Exception e)
{
   return BadRequest(e.Message);
}

This catches most of the cases but on the other hand, this procedure has some print messages that also get caught by this Exception .这可以捕获大多数情况,但另一方面,此过程有一些print消息也会被此Exception捕获。 Is there a way to catch the exception thrown only from RAISERROR and ignore this print message from SQL Server?有没有办法捕获仅从RAISERROR引发的异常并忽略来自 SQL 服务器的此print消息?

All info and error messages generated during command execution are buffered and available when a SqlException is caught.在命令执行期间生成的所有信息和错误消息都被缓冲并在捕获到SqlException时可用。 The Message property includes the text of all info messages (print statements and errors with a severity of less than 11) and the warnings/errors that caused the exception. Message 属性包括所有信息消息的文本(打印语句和严重性小于 11 的错误)以及导致异常的警告/错误。

To ignore info messages, use the SqlException Errors collection and process only those with severity (SqlError.Class property) of 11 or higher:要忽略信息消息,请使用 SqlException 错误集合并仅处理严重性(SqlError.Class 属性)为 11 或更高的那些:

catch (SqlException e)
{
   var sb = new StringBuilder();
   foreach(var error in e.Errors)
   {
       if(error.Class > 10) sb.AppendLine(error.message);
   }
   return BadRequest(sb.ToString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从SQL Server的RAISERROR中捕获C#中的错误? - How can i catch error in C# from RAISERROR of sql server? 过程(SQL Server 2014)中的Raiserror不能捕获客户端(C#) - Raiserror in procedure (SQL Server 2014) does not catch client side(c#) 使用 Dapper 读取时,如何从 SQL 服务器存储过程获取结果集和 RAISERROR 结果? - How can I get a resultset and a RAISERROR result from a SQL Server Stored Procedure when reading with Dapper? c#asp.net:从SQL存储过程中捕获raiserror()消息 - c# asp.net: capture the raiserror() message from an SQL stored procedure 在C#asp.net中的SQLraiserror输出 - SQL raiserror output in c# asp.net 如何在不使用catch异常的情况下从.NET应用程序检测sql server超时 - how to detect sql server timeout from .NET application without using catch Exception 客户端(C#)的更新过程未捕获过程(SQL Server 2005)中的Raiserror - Raiserror in procedure (SQL Server 2005) is not caught in update process in client side(c#) 使用 ExecuteScalar 在客户端(C# Winform)的 SQL 服务器中从 try/catch 中捕获错误 - Catch an error from try/catch in SQL Server at client side (C# Winform) using ExecuteScalar 捕获异常并保存到SQL Server - Catch exception and save to SQL Server 将 SQL `raiserror` 与 C# 中的 `select` 组合 - Combining SQL `raiserror` with `select` in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM