Is it OK to catch my exceptions in the controller's actions? Is there any better way of doing it? I'm actually catching my exceptions in the controller and using TempData to show a message to the user, but I have a weird feeling about this approach. I've been browsing around but I haven't found anything that suits me.
+4
A:
You can use the HandleError
attribute on the controller class to catch any unhandled exceptions and it will automatically return the Error.aspx view in the Shared folder. There are overloads for this attribute so you can only have it used for certain exception types, etc.
For more information on this approach, check out ScottGu's post about it: http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx
mc2thaH
2009-10-13 20:51:08
This is interesting, but the other way I can redirect to the standard views ("Index" for example) and display a personalized message for the concrete exception...
Carles
2009-10-13 21:13:40
The Error.aspx pages is tied to the HandleErrorInfo class, which exposes out the properties of the exception. If you are sending a personalized Exception Message, you can render that out to the view. Steve Sanderson's book "Pro ASP.NET MVC Framework" covers some ways to do this, and also how to create your own exception filters. I would recommend picking up that book.
mc2thaH
2009-10-13 22:56:47
Maybe extend the HandleError to allow definining the TempData? I think I'll investigate into this. Thanks...
Carles
2009-10-14 06:10:10
Still, not sure if this is the way to go... :P
Carles
2009-10-14 06:10:48
It seems to me like you need to implement your own Exception Filter. But before you do that, I would step back and make sure you are not over-complicating something that can be done with the built-in HandleErrorAttribute exception filter.
mc2thaH
2009-10-14 15:24:41