We hit this issue in one of our applications so I wrote a simple test console app to reproduce it. I have entity framework calling a SQL Server stored procedure, and when that stored procedure throws an error from the catch block, entity framework does not catch that error. It simply populates the result list with zero items but no error. I discovered that if I remove the try/catch from the stored procedure and throw the same error then EF does in fact catch it. However I need the try/catch as there’s other stuff I need to do there. I’ve seem some related posts where people aren’t actually populating the result set (not calling .ToList() or the like) and people are saying that running async was the issue but I called it synchronously and that didn’t change the outcome.
My simple test console app:
Program.cs:
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SQLExceptionTest.Models;
var builder = new DbContextOptionsBuilder<TESTNU40Context>();
builder.UseSqlServer("Data Source=MyServer; Initial Catalog=MyDB; Integrated Security=True; TrustServerCertificate=True");
var context = new TESTNU40Context(builder.Options);
try
{
var r = context.SQLExceptionTestResults.FromSqlInterpolated($"SqlExceptionTest").ToList();
Console.WriteLine($"Result count: { r.Count}");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
My stored procedure:
create procedure SqlExceptionTest
as
set nocount on;
begin try
select 1/0 as test;
end try
begin catch
-- EF doesn't catch this error
throw 51000, 'throw in catch', 1
end catch
If I execute the stored procedure from a query window I get the error I expect:
Msg 51000, Level 16, State 1, Procedure sqlexceptiontest, Line 15 [Batch Start Line 2]
throw in catch
So why is entity framework not catching the error? Thanks in advance for your help.