zalando / problem

A Java library that implements application/problem+json
https://zalando.github.io/problem
MIT License
880 stars 83 forks source link

How can I map validation errors? #486

Open cj19 opened 2 months ago

cj19 commented 2 months ago

I would like to override the default validation errors, but when I create a basic ControllerAdvice the handler does not get called. My handler:


@ControllerAdvice
public class DefaultExceptionHandler implements ProblemHandling {

    @Override
    @ExceptionHandler(value = { ConstraintViolationException.class })
    public ResponseEntity<Problem> handleConstraintViolation(ConstraintViolationException exception, NativeWebRequest request) {
        return null;
    }
}

My endpoint:


    @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<JwtResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        return authService.login(loginRequest);
    }

My security handler advice:

@ControllerAdvice
public class SecurityExceptionHandler implements SecurityAdviceTrait {
}

My websecurity config:


@Configuration
@EnableMethodSecurity
@Import(SecurityProblemSupport.class)
public class WebSecurityConfig {

    @Autowired
    private SecurityProblemSupport problemSupport;
....

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .csrf(AbstractHttpConfigurer::disable)
                .exceptionHandling(exception -> exception.authenticationEntryPoint(problemSupport)
                        .accessDeniedHandler(problemSupport))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                        .requestMatchers("/api/auth/**").permitAll().anyRequest().authenticated());

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}

What am I doing wrong?