- All Implemented Interfaces and Traits:
- MessageSourceAware
@CompileStatic
class ResponseFormattingDomainExceptionHandler
extends Object
implements MessageSourceAware
Handles shaping and internationalizing the body in HTTP responses when the execution of request results in throwing a DomainException.
Produced HTTP response body is a JSON serialized from OperationResponse instance containing populated metaData
and empty payload
properties. Here is an example:
{
"metaData": {
"general": {
"severity": "warning",
"locale": "en_GB",
"timestamp": "2020-04-26T09:41:04.917666Z"
},
"http": {
"status": "400",
"message": "Bad Request"
},
"violation": {
"code": "400",
"message": "Destination location cannot accept cargo from specified origin location.",
"type": "domain"
}
},
"payload": {}
}
Property metaData.violation.message
is intended to be localized. For localization to work, corresponding ViolationCode
property (contained in exception's ViolationInfo
property) has to be resolvable (ViolationCode.isResolvable()
returns true
). If this is not the case, hierarchical overriding of violation and exception messages is employed
according to the following rules:
- If
ViolationCode.resolvableMessageKey
is available, the exception renderer should use is for resolving a message through resource bundle.
-
Otherwise, the exception renderer should use
DomainException
message directly. Note that DomainException.message
is initialized to ViolationCode.codeMessage
if not set
explicitly to non-blank string.
When used from the Spring Boot application, the easiest is to create controller advice that is eligible for component scanning (@ControllerAdvice annotation is annotated with @Component):
@ControllerAdvice
class ResponseFormattingDomainExceptionHandlerControllerAdvice extends ResponseFormattingDomainExceptionHandler {
}
For localization purposes, we are defining responseFormattingDefaultMessages
resource bundle containing default messages. In the Spring Boot application, that resource bundle needs to be
configured, for example, in application.yml
file:
...
spring.messages.basename: messages,responseFormattingDefaultMessages
...
Localization message codes for metaData.violation.message
property is created with
MessageSourceResolvableHelper.makeMessageCodeListForViolationMessageOfDomainFailure method, where you can look
for further details. - See Also:
- MessageSourceResolvableHelper
- MessageSourceResolvableHelper.makeMessageCodeListForViolationMessageOfDomainFailure