I have an ASP.Net Core 2 web api project.
I have added the following to the Configure
method in my Startup.cs file
app.UseExceptionHandler();
I noticed in my Postman tests that I was getting an "Unable to get response" result. Server-side logging shows that the error has to do with Tables being missing from my Database. Which is fine, I can resolve that. But my question is why would the server not be returning a 500 Internal Server Error? Why is it dying, and returning no response at all to Postman?
So, in my Controller, I purposely throw an Exception to test the handler, and call the URL from Postman, and indeed, I get back a 500 Internal server error response, as expected.
Why are the "deeper down" errors being thrown from EFCore not being handled by the ExceptionHandler middleware, and crashing my app? Am I missing something?
Approach 1: UseExceptionHandler. Switch to the production mode for the app, startup file Configure method tells us: ASP.NET Core handles exception by calling UseExceptionHandler: public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env. IsDevelopment()) { app.
Use the UseExceptionHandler middleware in ASP.NET Core So, to implement the global exception handler, we can use the benefits of the ASP.NET Core build-in Middleware. A middleware is indicated as a software component inserted into the request processing pipeline which handles the requests and responses.
In your startup.cs, move the UseMvc()
tag to the bottom of the pipeline i.e.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseExceptionHandler();
app.UseMvcWithDefaultRoute();
}
In my case, the request pipeline faulted on startup when the route launched by the browser did not exist. In that scenario, my app.UseExceptionHandler() before the app.UseMvc() was not executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With