Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Exceptions that happen in a asp.net MVC Controller Constructor

What's the best way to handle exceptions that happen from within a controller's constructor?

All I can think of to do is use Application_OnError() or put a try/catch in my ControllerFactory.

Neither of these solutions seem ideal. Application_OnError is to broad - I have some non-mvc content in the site that has its own error handling.

Using a try/catch block seems kinda hacky.

If I'm serving different content type -html/text/json/rss.... I would like to be able to handle the exception from within the action method instead of having to write all kinds of conditions to determine what kind of error message to serve.

Am I missing something here, or has anyone else dealt with this?

like image 504
Jason Avatar asked Apr 22 '10 22:04

Jason


People also ask

How many ways are there to handle exceptions in MVC?

In ASP.NET MVC we may have three ways to handle exceptions, Try-catch-finally. Exception filter. Application_Error event.

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

The HandleErrorAttribute is the default implementation of IExceptionFilter. 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.

What is an exception how exceptions are handled in ASP NET application?

Exception class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the call stack to a place where the application provides code to handle the exception. If the application does not handle the exception, the browser is forced to display the error details.


1 Answers

If an exception is happening in your ControllerFactory when creating the controller in the first place, there's no way you can ever handle the exception in an action method.

Personally I would just do a try/catch, instantiate some error handling controller, and route the request through it instead.

A better question is - what are your controllers so dependent on that isn't being met that they have to throw exceptions when they're being constructed? Ostensibly, simply creating the controllers shouldn't be a huge source of exceptions. If they are, maybe you could look at lazily instantiating the dependencies in the action methods (rather than the constructor), and implementing an ErrorHandlingController approach. This would push the exceptions "down" into the controllers themselves, so you could take a more controller-centered approach to handling them.

like image 165
womp Avatar answered Sep 27 '22 19:09

womp