Skip to content

Instantly share code, notes, and snippets.

@dev-techmoe
Last active April 27, 2023 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dev-techmoe/f4c82af9335b7f218caf7a659a2cd439 to your computer and use it in GitHub Desktop.
Save dev-techmoe/f4c82af9335b7f218caf7a659a2cd439 to your computer and use it in GitHub Desktop.
[2023] How to use @ControllerAdvice to handles 404 errors correctly in a Spring Boot project

How to use @ControllerAdvice to handles 404 errors correctly in a Spring Boot project

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

Steps

  1. set this below to your application.yml
mvc:
  throw-exception-if-no-handler-found: true
web:
  resources:
    add-mappings: false
  1. create your ControllerAdvice
@Component
@ControllerAdvice
public class ControllerExceptionHandler  {
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public String noHandlerFound() {
        return "404 error got";
    }
}
  1. test your code, enjoy!

Feel free to post comments if you have any questions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment