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.
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.
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.
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.
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.
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