Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core UseExceptionHandler not handling all exceptions?

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?

like image 220
Shawn de Wet Avatar asked Feb 28 '18 09:02

Shawn de Wet


People also ask

How do I handle exceptions in ASP.NET Core Web API?

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.

How do you handle exceptions globally in .NET Core?

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.


1 Answers

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.

like image 135
Neil Avatar answered Sep 19 '22 17:09

Neil