ASP.NET MVC Global error handling

后端 未结 3 1248
夕颜
夕颜 2021-02-08 09:37

I have a custom HandleError attribute that deals with errors on the MVC pipeline; I have an protected void Application_Error(object sender, EventArgs e)

相关标签:
3条回答
  • 2021-02-08 10:18

    Application_Error might be the recommended way of handling errors in ASP.NET WebForms. But not in MVC.

    We got error filters that take care of errors for us. The problem with the filter is that it only works when a controller has been invoked. Which is the problem for 404 and 401 errors (not found and authorization) and your database connection problem.

    customErrors is the way to go here. I don't see why the redirect should be a problem?

    I'm going through proper error handling in a blog article: http://blog.gauffin.org/2011/11/how-to-handle-errors-in-asp-net-mvc/

    0 讨论(0)
  • 2021-02-08 10:19

    You haven't shown how exactly are you handling the errors in your Application_Error event nor how does your custom HandleAttribute is implemented so it's hard to guess what the problem might be. A common problem to watch for when implementing Application_Error is that you render some error view which itself throws an error. Think for example an error view that depends on a Layout and inside this layout you are calling a Html.Action helper to render the contents of another action that itself does database access and stuff. Your error views should be as static as possible. Ideally you should have a different Layout for them to avoid those kind of situations.

    I may also suggest you taking a look at the following approach for handling errors.

    0 讨论(0)
  • 2021-02-08 10:35

    To be correct to our visitors and the search engines, we should return meaningful HTTP status codes if errors occur, facing our site. It's not fair to return HTTP status code 200 on error, even if at the same time we return a view, explaining that an error occurred. if the user types in an incorrect address (the most frequent user fault), we should return HTTP status code 404 and not return or redirect to a View, where status code 200 will be returned.
    There is a short and clean recommendations summary HERE.

    0 讨论(0)
提交回复
热议问题