Handling Exceptions that Occur in Asp.net MVC Controller Designer

What is the best way to handle exceptions that come from the controller constructor?

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

None of these solutions seem perfect. Application_OnError - wide - I have some non-mvc content on a site that has its own error handling.

Using a try / catch block seems unreliable.

If I serve a different content type -html / text / json / rss .... I would like to be able to handle an exception from the action method instead of writing all kinds of conditions to determine what kind of error message to serve.

Am I missing something, or did someone else handle this?

+4
source share
1 answer

If you create an exception in your ControllerFactory when creating the controller first, you will not be able to handle the exception in the action method.

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

The best question is: which controllers are so dependent on what is not being implemented that they have to throw exceptions when they are being built? Allegedly, just creating controllers should not be a huge source of exceptions. If this is the case, perhaps you could lazily create dependency instances in the action methods (and not in the constructor) and implement the ErrorHandlingController approach. This will result in a down exception in the controllers themselves, so you can use a more controller-oriented approach for their processing.

+6
source

Source: https://habr.com/ru/post/1307734/


All Articles