[英]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.