Belgrade-SqlClient
Belgrade-SqlClient copied to clipboard
Errors thrown in SqlPipe.OnError do not propagate to middleware Error Handler
I have a Controller method as below: ` [HttpGet] public async Task NonExistentTable() { await SqlPipe .OnError(ex => { this.Response.StatusCode = 500; throw ex; } ) .Stream("select * from NonExistentTable FOR JSON PATH", Response.Body, "[]");
}`
and in the Startup.cs I have as below in the Configure: ` app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { context.Response.StatusCode = 500; // or another Status accordingly to Exception Type context.Response.ContentType = "application/json";
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
var ex = error.Error;
var err = new ErrorDto()
{
Code = 500,
Message = ex.Message // or your custom message
}.ToString();
await context.Response.Body.WriteAsync(Encoding.ASCII.GetBytes(err), 0, err.Length).ConfigureAwait(false);
}
});
});`
When the NonExistentTable API is called, the exception thrown inside the OnError handler, doesn't get handled in the UseExceptionHandler..
The issue happens only when SqlPipe.Stream is used, any other exception thrown from other methods gets handled as expected..
What am I missing here?
I have investigated this, but it is not a problem in data access. Callback catches the exception (I have added a test that verifies this), but it seems that in ASP.NET middeware is executed before callbacks in async methods. I still cannot confirm that this is the problem. Have you tried to define synchronous method with sync callback?
Jovan:
Thanks for looking into this.
Yes, I do see that your callback catches the exception. But when I throw the exception, I was hoping that the middleware IExceptionHandlerFeature will handle it and that did not happen.
No, I haven't tried sync but I have feeling that it might work in that case..