- All Implemented Interfaces and Traits:
- MessageSourceAware
@CompileStatic
class ResponseFormattingSpringMvcExceptionHandler
extends ResponseEntityExceptionHandler
implements MessageSourceAware
Handles shaping and internationalizing the body in HTTP responses when the execution of request results in throwing SpringMvc specific exceptions.
SpringMvc exceptions taken into account are those that are handled by SpringMvc own ResponseEntityExceptionHandler, which is also the parent of this class.
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": "2021-02-09T10:09:36.354151Z"
},
"http": {
"status": "405",
"message": "Method Not Allowed"
},
"violation": {
"code": "405",
"message": "Request is not valid.",
"type": "other"
}
},
"payload": {}
}
For error
severity, the response body also contains metaData.violation.logUuid
property with the value of generated UUID. That UUID is part of the message logged for the exception.
For warning
severity, there is no logging of the exception.
In the response above, property metaData.violation.message
needs to be localized.
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 ResponseFormattingSpringMvcExceptionHandlerControllerAdvice extends ResponseFormattingSpringMvcExceptionHandler {
}
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.makeMessageCodeListForViolationMessageOfInfrastructureWebFailure method, where you can look
for further details. - See Also:
- MessageSourceResolvableHelper
- MessageSourceResolvableHelper.makeMessageCodeListForViolationMessageOfInfrastructureWebFailure