Since many online tutorials are misleading, I want to share how I solved this problem.
The version of my spring boot used: 2.7.11
- set this below to your
application.yml
mvc:
throw-exception-if-no-handler-found: true
web:
resources:
add-mappings: false
- create your ControllerAdvice
@Component
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseBody
public String noHandlerFound() {
return "404 error got";
}
}
- test your code, enjoy!
Feel free to post comments if you have any questions.