I am wondering what is the best way to build messages in controller based on a service result, to the front end. I am thinking in java/spring context using rest controllers, but it reflects the MVC model as well. Obviously the examples I have seen on the internet are way to simple to understand what are best practices in real world application. So, to the case, let's assume a following scenario:
- We have an controller CalculateController with a single method doMath(int a, int b)
- We have a service CalculatorService that perform the math it self in the doMath(int a, int b) method.
- We want to perform additional validation on input parameters. The method is called validateInput(int a, int b).
- We want to send as a response calculation result, or a specific information, why it failed.
So now the questions:
As a result of controller method execution, I would retuun a Map of objects, that will be parsed into JSON. Possible entities would be:
{ "result":"12" }
{ "errorCode":"incorrect parameters" }
is this correct, or should I aim into different error handling? I know that I could additionally use a http error codes for example 400, or 406 to indicate that input parameters are incorrect, but personally I prefer not to use http error codes to indicate application logic result. (I consider input validation as appliaciton logic)
- Where the validateInput method should be placed, in controller, or in service?
- In the validateInput method I want to check two simplified conditions
a) is a < b and then inform user with a message "a cannot be smaller than b"
b) is a*a == b and then inform user with a message "a squared cannot be equal to b".
How should I provide the additional message based on the result? I can think of two solutions:
- return Map, that in case of positive validation result has result = true, and in case of negative result result = false, and errorCode with corresponding message
return boolean value indicating validation result, and additionally use exceptions for negative result. (bonus question, in such scenario should the exception be checked or unchecked?)
- For service method it should be handled the same way?