11

I want to override html error page for 404 responses as an JSON response. When i use @ControllerAdvice without @EnableWebMvc it is not working.

@EnableWebMvc   // if i remove this, it is not working
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalControllerExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<ZeusErrorDTO> noHandlerFoundException(
                    HttpServletRequest request, 
                    NoHandlerFoundException exception) {

        ErrorDTO errorDTO = new ErrorDTO();
        return new ResponseEntity<>(errorDTO, HttpStatus.NOT_FOUND);
    }
} 

Is there an option for custom exception handling without @EnableWebMvc, because it overrides Spring configurations which are declared inside application.yml.

utkusonmez
  • 1,386
  • 14
  • 21

3 Answers3

11

Normally @utkusonmez answer works fine but not in my case, as I am using swagger. So all I did is add following properties in my application.properties file

spring.mvc.throw-exception-if-no-handler-found=true
spring.mvc.static-path-pattern=/swagger*

Now both NoHandlerFoundException and swagger-ui works fine.

Emdadul Sawon
  • 5,122
  • 2
  • 42
  • 46
  • 2
    This answer was very appreciated. Many other questions on this topic had suggesting using "static-locations" or enabling resource mapping entirely, but only "static-path-pattern" allowed Swagger to work without affecting exception handling. – J. Marciano Jul 15 '19 at 20:30
  • 1
    This answer is really appreciated since I work with swagger and it enables us to customize and handle the no handler exception without affecting the swagger-ui. – Sreedhar S Mar 24 '20 at 11:18
10

I easily resolved problem by adding one of configurations in application.yml.

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

or

spring.mvc.throw-exception-if-no-handler-found=true
spring.mvc.static-path-pattern: /static

If you don't restrict Spring and no handler matches with your request, then spring tries to look for static content.

utkusonmez
  • 1,386
  • 14
  • 21
2

This is happening because, using @EnableWebMvc disables MVC autoconfiguration and asks you to provide exactly what You want. Have a look at this link
You can either use other means to customize your configuration, such as a @Configuration See Boot's WebMvcAutoConfiguration to find out what the defaults are, and copy over the pieces that you need.

This Link might help You as well -> LINK

What should you do when you want to customize your beans? As usual, extend WebMvcConfigurerAdapter (annotate the new class with @Component) and do your customizations.
So, bottom line of the particular problem: Don’t use @EnableWebMvc in Spring Boot, just include spring-web as a maven/gradle dependency and it will be autoconfigured.

This answer on stackoverflow shows how to do this .. check this LINK3

Tahir Hussain Mir
  • 2,348
  • 2
  • 19
  • 25