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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With