ASP.NET MVC exception handling
Asked Answered
T

1

19

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.

Trabzon answered 13/10, 2009 at 20:46 Comment(1)
This is old but I just wanted to provide my post as ref (issues with HandleError) while passing by - #12184153Ansate
C
11

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

Corvine answered 13/10, 2009 at 20:51 Comment(5)
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...Trabzon
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.Corvine
Maybe extend the HandleError to allow definining the TempData? I think I'll investigate into this. Thanks...Trabzon
Still, not sure if this is the way to go... :PTrabzon
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.Corvine

© 2022 - 2024 — McMap. All rights reserved.