I have a complex Spring Boot (version 2.7.18) application that I need to capture all errors and exceptions and return a generic error message to the user. The error/exception will be logged for research but the user will only receive the generic message “…your request could not be completed…”. I believe a ResponseEntityExceptionHandler can be configured to catch all errors/exceptions. Please correct this first statement if I am wrong.
Spring annotations and Spring Boot defaults enables my application to serve a single page web application (Angular) to the browser. After the web application is bootstrapped in the browser, my Spring application also hosts REST endpoints and hosts a Websocket server which are both utilized only by the web application.
I need to handle 400 Bad Requests, 500 Internal Server Errors, as well as exceptions thrown from my REST endpoints. I was able to solve the last case, REST exceptions from my endpoints by implementing a HandlerExceptionResolver.
For all of the other errors and exceptions I have tried to implement the solution presented in this post Spring Boot REST service exception handling. However, when I try to implement that solution this breaks my application.
When I add @EnableWebMvc to the @ControllerAdvice class my web application will not load in the browser and any link that I try to “Get” just forwards me to the configured “/error” mapping. For example a Get to “index.html” that used to work now fails.
Another issue, (even without added @EnableWebMvc) is if I added the recommended changes to application.properties which are:
spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=false
This change causes any Get to return the exception:
org.springframework.web.servlet.NoHandlerFoundException: No handler found for GET /index.html
The solution as presented clearly warns that using @EnableWebMvc will disable the autoconfiguration of Spring Boot.
I need one of two solutions
- Configure a ResponseEntityExceptionHandler along with all of the Spring Boot defaults?
- Include @EnableWebMvc, but configure the Spring Boot defaults.
3