I have a more general question about how to divide the code and responsibilities of the model, view and controller within the MVC pattern. For a better understanding I am going to use an example case.
My Question
The application is divided into the model, view and controller. How is an error handled during some operation at the model-level which should be displayed in the view ?
I thought of two possibilities:
a) The model saves an error string and notifies the controller and the view. The view then polls the error string from the model and saves it. Afterwards the controller tells the view to display the error.
b) The model returns the error to the controller which passes it to the view to be displayed.
What would you say would fit best to the MVC pattern ? Or what would be closer to the MVC pattern ?
Thank you very much in advance
There are mostly two approaches:
For the start we should remember about Command Query Separation (CQS) principle.
So we expect errors on commands when changing model state.
Your Model can either throw some kind of BusinesModelException
exception or have a return value of option type. None
then means success (no errors) and Some
contains information about error.
Having operation result allows more easily to aggregate errors during validation for example and explicitly through method's signature notify callers about returned errors. In C# for example if not documented properly it's not very obvious which exceptions can be thrown.
Exceptions are also not good for performance if you have a large batch of operations some of which return error.
When exception is not get thrown we usually imply that application does not have corrupted state and Operation result conveys this more naturally whereas exceptions require convention (whether it is recoverable or not).
On the other hand exceptions can travel across the layers to the point where they really need to be processed. This allows code to be cleaner: for example I do not need to catch biz logic exceptions at all but make an exception filter in MVC which correctly converts it to the appropriate htmls status code and error message. Also intermediate layers stay unaware of all the kitchen related to the errors.
Exceptions more easily fit into Aspect Oriented Programming as well.
These two approaches can be combined.
I prefer exceptions.