The common solution for handling bad requests is to set throwExceptionIfNoHandlerFound
in org.springframework.web.servlet.DispatcherServlet
class. You didn't mentioned which type of application you wrote, simple war archive with spring-mvc dependency or spring boot styled application.
For simple spring-mvc application, you can set that property in web.xml file:
...
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>throwExceptionIfNoHandlerFound</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
...
For spring boot application, you just need to set config property:
spring.mvc.throw-exception-if-no-handler-found=true
In both cases, DispatcherServlet
will throw NoHandlerFoundException
exception, in order to handle this exception, you need to add the ExceptionHandler
class as follows::
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<String> handleNoHandlerFoundException(NoHandlerFoundException ex) {
return ResponseEntity.status(404).body("Error occurred");
}
}
Note: When you enable throwExceptionIfNoHandlerFound
property, you should remember about static resources, and add custom mappings for them, otherwise the resources will not be found.
Configure static resources (Spring Boot):
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/resources/static/
or if there are no static resources:
spring.resources.add-mappings=false