11

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.

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! This is a nice approach.
what about using ELMAH?
@Murali I'm not a fan of ELMAH to be honest
Guys, what you think about what i added in Edit? Can custom route fetch to such incorrect behavior of HandleErrorAttriubute? Because i re-check it twice, and when route it default it works just fine as expected, no any other filters logic fires twice
@mattytommo what's your beef with elmah, out of curiosity?
|
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.