ControllerAdvice response still prints timestamp

39 views Asked by At
@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;
}
1

There are 1 answers

0
Jigar Shah On

found it MappingJackson2HttpMessageConverter()

MappingJackson2HttpMessageConverter(createObjectMapper())