- All Implemented Interfaces and Traits:
- MessageSourceAware
@CompileStatic
class ResponseFormattingConstraintViolationExceptionHandler
extends Object
implements MessageSourceAware
Handles shaping and internationalizing the body in HTTP responses when the execution of request results in failing validation, a.k.a. throwing a jakarta.validation.ConstraintViolationException.
Produced HTTP response body is a JSON serialized from OperationResponse instance containing populated metaData
and empty payload
properties. Here is an example:
{
"metaData": {
"general": {
"timestamp": "2021-03-03T18:30:03.635859Z",
"severity": "warning",
"locale": "en"
}
"http": {
"status": "400",
"message": "Bad Request"
},
"violation": {
"code": "400",
"message": "Request is not valid.",
"type": "validation",
"validationReport": {
"root": { "type": "bookCargoCommandRequest" },
"constraintViolations": [
{ "type": "notNull", "scope": "property", "path": "destinationLocation", "message": "must not be null", "invalidPropertyValue": "null" },
{ "type": "notNull", "scope": "property", "path": "originLocation", "message": "must not be null", "invalidPropertyValue": "null" }
]
}
}
},
"payload": {}
}
Following properties need to be localized: metaData.violation.message
and metaData.violation.validationReport.constraintViolations[].message
.
It is important to realize that during localization of metaData.violation.message
, metaData.violation.validationReport.root.type
is included as a messageSubType
. That way,
if needed, metaData.violation.validationReport.root.type
can have an influence on resolved message.
Message codes for these properties are created with utility methods from MessageSourceResolvableHelper. Look there for more details.
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 ResponseFormattingConstraintViolationExceptionHandlerControllerAdvice extends ResponseFormattingConstraintViolationExceptionHandler {
}
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
...
- See Also:
- MessageSourceResolvableHelper