0

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?

Regyn
  • 515
  • 3
  • 12
  • Have a look for 'RFC 7807' one the one hand and https://stackoverflow.com/questions/12806386/is-there-any-standard-for-json-api-response-format on the other hand, too. – blafoo Feb 14 '22 at 09:50

0 Answers0