Reputation: 1946
I have a question about the best way of using HandleErrorAttribute in my MVC 5 application. As we know, we can add this attribute to global filters like that:
filters.Add(new HandleErrorAttribute{View = "Error"});
This involves the app to show the 'Error' view every time when an unhandled exception is thrown in any level of app. But, if I have some logic in another global authorize or action filter, that produces some exception, then when the exception is thrown for first time, the app tries to redirect to the Error View, again other filters begin executing and produce the same exception again, so asp.net to avoid looping terminates the app. So what is the best way to use this HandleErrorAttribute to avoid such behavior? Thanks!
Edit: After some debugging I found that this is not the usual behavior of HandleErrorAttribute, so looping happens for me only when I use custom Routes f.e.
{key}/{controller}/{action}
and when some error occurs in the filter logic, then the app tries to redirect to the Error View, but again another filter logic begins to exectue and I even see an "Error" value in the {key} route parameter, so it is unwanted behavior.
When I use the default route {controller}/{action}
this doesn't happen and I get exactly to the Error View without executing any global filter logic a second time.
Upvotes: 11
Views: 34242
Reputation: 1407
Matt is right about global.asax... this is the example I followed http://www.digitallycreated.net/Blog/57/getting-the-correct-http-status-codes-out-of-asp.net-custom-error-pages
Then in each view I added: Response.StatusCode = 500; or which ever other code I wanted to show back to the client.
Upvotes: 3
Reputation: 56429
You should wrap your action filter logic inside a try
catch
, then inside the catch
block, redirect to the Error
view and pass the Exception
.
Your only other alternative is to ditch HandleError
completely and use the Application_Error
event inside Global.asax to manage your error handling. That way you can redirect to your Error
action inside there regardless of where the error occured.
Upvotes: 11