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.
Exception filter in MVC provides an ability to handle the exceptions for all the controller methods at a single location. This is by creating a class, which inherits from the FilterAttribute and IExceptionFilter interface.
HandleError Attribute This filter handles all the exceptions raised by controller actions, filters, and views. To use this feature, first of all turn on the customErrors section in web. config.
This default way of handling exception where we write our source code into the try bock and catch exception in catch block. However you can have multiple catch blocks for a try block. Even you can have Try –catch block inside Try block.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With