简体   繁体   中英

Catch RAISERROR from SQL Server in .NET

I have a stored procedure in SQL Server that throws an error whenever a condition is hit. 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 . Is there a way to catch the exception thrown only from RAISERROR and ignore this print message from SQL Server?

All info and error messages generated during command execution are buffered and available when a SqlException is caught. 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.

To ignore info messages, use the SqlException Errors collection and process only those with severity (SqlError.Class property) of 11 or higher:

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM