Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Core Web app: Global exception handling using IExceptionFilter vs custom middleware

Asp.Net Core supports two ways to do global exception handling for a Web Application, implementing IExceptionFilter or by creating custom middleware. Is there any advantage of one over the other? Most references I see are for creating custom middleware.

like image 705
frosty Avatar asked Dec 26 '17 17:12

frosty


People also ask

What is the best way to handle exceptions globally in ASP.NET Core?

The middleware UseExceptionHandler can be used to handle exceptions globally. You can get all the details of the exception object (Stack Trace, Inner exception, message etc..) and display them on-screen. You can implement like this.

How does ASP.NET handle exceptions globally?

ASP.NET Core Error Handling You can register it as a global filter, and it will function as a global exception handler. Another option is to use a custom middleware designed to do nothing but catch unhandled exceptions. You must also register your filter as part of the Startup code.

How many ways can exceptions be handled in .NET Core?

For Production environment, 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. UseDeveloperExceptionPage(); } else { app.


1 Answers

The ASP.NET Core docs explains the main differences between these two approaches. It states that exception filters:

  • Handle unhandled exceptions that occur in Razor Page or controller creation, model binding, action filters, or action methods.
  • Do not catch exceptions that occur in resource filters, result filters, or MVC result execution.

There's even advice for when to use middleware and when to use exception filters:

Exception filters:

  • Are good for trapping exceptions that occur within actions.
  • Are not as flexible as error handling middleware.

Prefer middleware for exception handling. Use exception filters only where error handling differs based on which action method is called. For example, an app might have action methods for both API endpoints and for views/HTML. The API endpoints could return error information as JSON, while the view-based actions could return an error page as HTML.

like image 76
Kirk Larkin Avatar answered Sep 28 '22 04:09

Kirk Larkin