Spring boot - @ControllerAdvice doesn't work

Viewed 484

I am using Spring Boot 2.3.1, I try to make a custom ExceptionHandler,

Here is my CustomHandler class:

@ControllerAdvice()
public class AppExceptionHandler extends ResponseEntityExceptionHandler{
    
        @ExceptionHandler(value = {Exception.class, RuntimeException.class, NullPointerException.class})
        public ResponseEntity<Object> handleAnyException(Exception ex, WebRequest request){
            System.out.println("===>App Exception was callled....!");
            return new ResponseEntity<>(
                    ex, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
      
    }

And my project structure:

enter image description here

I can't get any response from this class, it seems like it was not loaded.

Thanks.

1 Answers

Your package structure is the problem. Since the root package is id.tarmizi.demoapi the package name for your handler should be id.tarmizi.demoapi.exceptions instead of id.tarmizi.demoap.exceptions (an i is missing).

Keep in mind that all Spring boot classes should be under the root package, unless you explicitly configure it, see the documentation

Related