Here is my stored procedure code called "uspTest"
BEGIN TRY
SELECT 3 / 0;
END TRY
BEGIN CATCH
RAISERROR('D', 16, 3);
END CATCH
And Here is my c# code in visual studio
public IHttpActionResult RegisterUser(RegisterModelView registerViewModel)
{
try
{
using (AusHerbEntities ctx = new AusHerbEntities())
{
ctx.uspTest();
Console.Write("i am in try block");
}
}
catch (Exception e)
{
Console.Write(e.Message);
}
return Ok();
}
When I run this code, the Catch block in C# code is not called, but I expect it to be called because the Stored Procedure raises error.
How can I get this code work?
I just want to do RAISERROR in catch block in Stored Procedure and catch the error in c# code.
To make SqlException
thrown, the stored procedure must return with @@error
set. In your case, END CATCH
statement clears @@error
. Inserting a RETURN
statement immediately after the RAISERROR
statement should make SqlException
thrown.
BEGIN TRY
SELECT 3 / 0;
END TRY
BEGIN CATCH
RAISERROR('D', 16, 3);
RETURN;
END CATCH
Do you need the try-catch in SQL? If you're only using it to rollback the transaction, then you can simply set XACT_ABORT ON and dispense with the try-catch. The transaction will be rolled back, and any error will bubble through to the client. Here is a good article on the subject: https://www.simple-talk.com/sql/t-sql-programming/defensive-error-handling/
Can't see all your c# code but replace; catch (Exception e) with catch(SqlException e)
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.