Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
Spring MVC CORS not working for error controllers

I have my Spring MVC application configured to use CORS as such:

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**");
}

This works fine for successful requests however when an exception is thrown and is picked up by my error handler, CORS headers are not added.

@ControllerAdvice
public class ApiErrorHandler {

   @ExceptionHandler(value = HttpClientErrorException.class)
   public ResponseEntity badRequest(Exception ex) 
   {
       return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ErrorBodyWrapper.wrapErrorInJson(ex.getMessage()));
   }
}

Is there a reason CORS does not work for error handlers?

Thanks

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I think by default the only method added to the mapping is GET, In your "addCorsMappings" try to specify the methods you want to add the header to

       registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD");
about 4 years ago · Santiago Trujillo Report

0

Using Spring CorsFilter can resolve this problem.

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);

        config.addAllowedOrigin("*");

        config.addAllowedHeader("*");
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));

        bean.setOrder(0);
        return bean;
    }
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!