问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/47981785/asp-net-core-web-app-global-exception-handling-using-iexceptionfilter-vs-custom