Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom exception handler for NoHandlerFoundException is not working without @EnableWebMvc

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.

like image 238
utkusonmez Avatar asked Mar 08 '18 06:03

utkusonmez


2 Answers

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.

like image 90
Emdadul Sawon Avatar answered Oct 21 '22 18:10

Emdadul Sawon


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.

like image 40
utkusonmez Avatar answered Oct 21 '22 19:10

utkusonmez