The sine that you plan to use the REST api, you need to create your own Pojo (aka. Resource), which will be odd behavior or validation errors, as indicated by horaceman. I will show you how we do this in our application.
Since we use JSON as a representation of the data, we want the following information if an unexpected exception occurs.
{ "status" : "EXCEPTION", "exceptionName" : "MyCustomException", "exceptionMsg" : "ex.unsupportedOperation" }
This, of course, is an example. A good solution is that we can consider exceptionMsg
as a key in our interface to display the correct i18n
message or display it to the user as is (in this case we use more descriptive messages).
Now that everything is all right, we are doing something like this:
{ "status" : "OK", "data" : {(...)} }
Element
Data
is optional. We can send everything we need to notify the interface, or skip it completely.
The final scenario will be yours - validation errors. In this case, we usually send the following content:
{ "status" : "VALIDATION_FAILED", "errors" : [ "fieldName" : "username", "errorCode" : "validation.requiredField", "errorMsg" : "Username is required."] }
Thus, it is obvious that the API clients will receive information that the verification failed, and in the appropriate fields, accurate information about what went wrong. Of course, errors
is an array (or List
), so we always provide as much detail as necessary.
How am i doing this? Easy, these objects are simple POJOS that translate to JSON using Jackson. This gives me unlimited JSON presentation capabilities. What I am doing, I am ready by POJO to present validation errors (for example) and add it as a Model
to my ModelAndView
instance. Then I just rely on Spring for proper JSON marshaling.
In your case, you have an @ResponseBody
annotation with your Post
instance, as far as I know, you cannot do this. Your setup says, “Well, no matter what happens, always return an instance of Post.” What you have to do is replace it with a simple ModelAndView
, provide it with the correct Model
based on validation, and return it to the client API.