Assume I want to return messages in a messages json array attribute in a reponse. These messages can be Warnings, Information or Errors.
Something like
{
"data": {...},
"messages": [
{ "type": "W", "id": "QQQ/123", message: "Non ASCII used in identifier" },
{ "type": "I", "id": "QQQ/124", message: "Job scheduled at cluster 7" }
]
}
or
{
"error": {...},
"messages": [
{ "type": "W", "id": "QQQ/123", message: "Non ASCII used in identifier" },
{ "type": "E", "id": "QQQ/127", message: "Attribute X has invalid value Y" },
{ "type": "E", "id": "QQQ/127", message: "Attribute A has invalid value B" }
]
}
How would I design @Services so something like this is supported? The only way I could see is that every service returns a MessageResponse<T> as a wrapper which contains messages.
So I'd have
MessageResponse<XYZ> xyz = new MessageResponse<>();
MessageResponse<Job> jobResponse = jobService.createJob(jobDTO);
xyz.appendMessagesOf(jobResponse);
if (jobResponse.hasError()) {
return xyz;
}
xyz.addInfoMessage(new Message("QQQ/124", id));
This of course means I no longer can use exceptions, or design every exception so the currently collected messages can be appended.
Is there any known pattern to do it better than my approach?