The solution for this problem is:
- Configure DispatcherServlet to throw and exception if it doesn't find any handlers.
- Provide your implementation for the exception that will be thrown from DispatcherServlet, for this case is the
NoHandlerFoundException
.
Thus, in order to configure DispatcherServlet you may use properties file or Java code.
Example for properties.yaml,
spring:
mvc:
throw-exception-if-no-handler-found: true
Example for properties.properties,
spring.mvn.throw-exception-if-no-handler-found=true
Example for Java code, we just want to run the command servlet.setThrowExceptionIfNoHandlerFound(true);
on startup, I use the InitializingBean
interface, you may use another way. I found a very well written guide to run logic on startup in spring from baeldung.
@Component
public class WebConfig implements InitializingBean {
@Autowired
private DispatcherServlet servlet;
@Override
public void afterPropertiesSet() throws Exception {
servlet.setThrowExceptionIfNoHandlerFound(true);
}
}
Be careful! Adding @EnableWebMvc disables autoconfiguration in Spring Boot 2, meaning that if you use the annotation @EnableWebMvc then you should use the Java code example, because the spring.mvc.*
properties will not have any effect.
After configuring the DispatcherServlet, you should override the ResponseEntityExceptionHandler
which is called when an Exception is thrown. We want to override the action when the NoHandlerFoundException
is thrown, like the following example.
@ControllerAdvice
public class MyApiExceptionHandler extends ResponseEntityExceptionHandler {
@Override
public ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String responseBody = "{\"errormessage\":\"WHATEVER YOU LIKE\"}";
headers.add("Content-Type", "application/json;charset=utf-8");
return handleExceptionInternal(ex, responseBody, headers, HttpStatus.NOT_FOUND, request);
}
}
Finally, adding a break point to method handleException
of ResponseEntityExceptionHandler
might be helpful for debugging.