javaspringspring-bootjackson-modules

zalando problem-spring-web generates unwanted stack trace


I'm trying to implement RFC 7807 in my Spring Boot project using zalando problem-spring-web https://github.com/zalando/problem-spring-web

I've done the setup according to this guide https://github.com/zalando/problem-spring-web/tree/master/problem-spring-web

When an exception is thrown, the Problem instance does get generated, but its serialized JSON form is not as expected, most notably the stack trace is included when it shouldn't.

After some debugging, it seems that the ProblemModule is not registered in the ObjectMapper that is used to serialize the problem (its setupModule method is never called). I was under the impression that declaring a bean of type Module was enough to have it picked up by Spring and registered in the ObjectMapper, but it doesn't happen here.

The doc says

In case you want to enable stack traces, please configure your ProblemModule as follows:

ObjectMapper mapper = new ObjectMapper()
     .registerModule(new ProblemModule().withStackTraces());

which seems to imply that you need to instantiate your own ObjectMapper, but then how to make sure that it's used by the library when deserializing the Problem?


Solution

  • Since I can't get the ObjectMapper to register my Modules I figured I had to do it myself so I came up with this solution that seems to work:

    @Configuration
    public class ProblemConfiguration implements InitializingBean {
    
        @Autowired
        ObjectMapper objectMapper;
    
        @Override
        public void afterPropertiesSet() {
            objectMapper.registerModules(
                    new ProblemModule(),
                    new ConstraintViolationProblemModule()
            );
        }
    }
    

    If someone has an idea why it's not working as expected, I'd be glad to hear it :)