I have a simple Web API Core v3.1 where I am trying to handle Exceptions Globally. After following this answer https://stackoverflow.com/a/55166404/1508398, here is my code for doing that.
app.UseExceptionHandler(appBuilder => appBuilder.Run(async context =>
{
var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
var exception = exceptionHandlerPathFeature.Error;
var result = JsonConvert.SerializeObject(new { error = exception.Message });
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(result);
}));
The error I get is at context.Response.WriteAsync(result);
is :
System.ObjectDisposedException: Cannot access a closed Stream.
I am pretty sure I am missing something basic but unable to figure this out.
I essentially need to wrap the response into an object whenever an exception occurrs.