In the stored procedure of SQL Server, according to the requirements of the business logic, sometimes a custom exception needs to be thrown #ProgramCapture and perform corresponding processing.
SQL Server throws a custom exception and is simple, like this: raiserror ('rais error1 ', 16, 1) with Nowait
However, it is very important to determine what error levels are used. Otherwise, catch blocks in C # may not be captured.
The SQL servr can throw a custom exception in this way:
Raiserror ('rais error1', 16, 1) with Nowait
The number 16 indicates the error level:
The error level ranges from 0 to 25, of which 19 to 25 are major error levels.
Note: A value smaller than 0 is interpreted as 0, and a value greater than 25 is interpreted as 25.
Any user can specify the error level between 0 and 18.
Errors ranging from 19 to 25 can only be specified by members of the SysAdmin role using the with log option.
Errors of levels 19 to 25 are recorded in the error log and Application Log.
Errors of 20 to 25 levels are considered fatal. In case of a fatal level error, the client connection will terminate after receiving the message.
The Catch Block in C # can capture exceptions with error levels 11 to 19.
Errors of 0 to 10 levels are not caught at all. Exceptions of 20 to 25 levels are considered fatal and will be disconnected from the database. Therefore, the C # cath block can accept this exception,
However, the exception content is not a real exception content. It may be something like this: "A transmission-level error occurs when receiving results from the server ".
Public Static Void Getsqlerror ()
{
Try
{
String Constring = " Server = (local); uid = sa; Pwd = SQL; database = test1 " ;
String SQL = " Select * from T1 " ;
String Raiserror = " Raiserror ('rais error1', 16, 1) with Nowait " ;
SQL = SQL + " ; " + Raiserror;
Sqlconnection con = New Sqlconnection (constring );
Sqlcommand cmd = New Sqlcommand (SQL, con );
Con. open ();
Cmd. executenonquery ();
Con. Close ();
}
Catch (Exception ex)
{
Console. writeline (ex. Message );
}
}