@ControllerAdvice
public class GlobalExceptionHandlerAdvice extends ResponseEntityExceptionHandler {
@Override
public ResponseEntity<Object> handleServletRequestBindingException(
ServletRequestBindingException servletRequestBindingException, HttpHeaders headers, HttpStatus status, WebRequest request) {
return ErrorResponse.builder(e, status, errorMessage)
.property("code", String.valueOf(applicationError.getCode()))
.property("timestamp", OffsetDateTime.now())
.build();
}
}
I have added Object mapper as required. Still it prints time stamp. Strange thing is, if I add @ExceptionHandler in Controller (instead of advice), it prints it correctly.
MockMvc mock = MockMvcBuilders.standaloneSetup(myController)
.setMessageConverters(new MappingJackson2HttpMessageConverter(createObjectMapper()))
.setHandlerExceptionResolvers(createExceptionResolver())
.build();
private ExceptionHandlerExceptionResolver createExceptionResolver() {
ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver() {
@Override
protected ServletInvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod handlerMethod, Exception exception) {
Method method = new ExceptionHandlerMethodResolver(GlobalExceptionHandlerAdvice .class).resolveMethod(exception);
return new ServletInvocableHandlerMethod(new GlobalExceptionHandlerAdvice(), method);
}
};
exceptionResolver.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
exceptionResolver.afterPropertiesSet();
return exceptionResolver;
}
public ObjectMapper createObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return objectMapper;
}
found it MappingJackson2HttpMessageConverter()