How to avoid using try ... catch in controllers?

I am trying to handle my exceptions in the lower layers of my application, as they can be processed (register them). However, there are errors that should cause the application to crash, for example, if the parameter is NULL and should not throw an ArgumentNullException in this case.

If you take into account the level of the controller calling the service level. I want the service level not to throw exceptions, because I want to handle everything here (logging), but I fell, as it is impossible in this case (for example, in the case of NULL).

So what is the best way to avoid using try ... catch in controllers? or should I use try ... catch in the controller?

+4
source share
2 answers

I prefer to handle all unhandled exceptions (things that shouldn't happen) in the Application_Error method. Here you can register an exception and, based on its nature, show the correct idea of ​​the error.

Things like custom model bindings, validators, action filters, ... can also allow you to intercept some exceptional conditions so as not to damage your controllers with try / catch.

For everything that I intend to handle, for example, business errors, etc., there is nothing wrong with using try / catch or it is even better to use if and have a service level notifying you of TryXXX .)

So, as always, the answer to your question is: it depends. It depends on how your application is organized, how your service level is organized, what potential errors can occur, what errors you would like to explicitly handle ... many, many, many factors and, of course, many, many, many possible solutions.

+7
source

Collaborate with Darin Dimitrov

Things like custom model bindings, validators, action filters, ... can also allow you to intercept some exceptional conditions to avoid polluting your controllers with try / catch everywhere.

This is what I prefer. You can make an IExceptionFilter that looks like this:

 public class ExceptionLoggingFilter : IExceptionFilter { private ILogger _logger; public ExceptionLoggingFilter(ILogger logger) { _logger = logger; } public void OnException(ExceptionContext context) { Exception ex = context.Exception; if (_logger != null) { _logger.log(ex) } } context.ExceptionHandled = true; //see note } 

Note: if you do not want to re-create the exception, you can add this. If you only want to register, but have a different filter to transmit it, you can delete this line.

then in your Global.aspx you will do the following:

 public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new ExceptionLoggingFilter(new Log4NetLogger())); } 

I prefer to create filters to create Application_Error , because it makes it easier for me to separate the various functions. (e.g. logging, checking if the application can handle it, etc.)

+3
source

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


All Articles