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

限于喜欢 提交于 2019-12-10 17:16:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!