Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC exception handling

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.

like image 681
Carles Company Avatar asked Oct 13 '09 20:10

Carles Company


People also ask

What are the exception filters in MVC?

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.

Which of the following codes shows how exceptions are handled in MVC?

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.

Can we use try catch block in MVC?

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.


1 Answers

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

like image 190
mkchandler Avatar answered Oct 21 '22 11:10

mkchandler