1

I'm using @ControllerAdvice in Spring Boot project to handle Stripe's Card Exception but every time when this exception is thrown the code to handle Exception works instead of the code to handle specific Card Exception.

this is what I am doing :

"This is the Api that throws he exception - CardException on entering wrong Card details"

@PostMapping("/charge")
    public String chargePayment(HttpServletRequest request) throws CardException, AuthenticationException, InvalidRequestException, StripeException { 
.......
}

"This is my Exeption handling class code"

@ControllerAdvice
public class StripeExceptionHandler {

// I want this to work when the above method/Api throws CardException.
    @ExceptionHandler(CardException.class)
    public String handleCardException(CardException cardException, Model model) {
        model.addAttribute("exception","CardException : "+ cardException.toString());
        model.addAttribute("redirectUrl", "contribute");
        return "exceptionpage";
    }

// But every time CardException is thrown this code works instead of the above specific code.
    @ExceptionHandler(Exception.class)
    public String handleGlobalExceptions(Exception exception, WebRequest webRequest, Model model) {
        model.addAttribute("exception", exception.getMessage());
        model.addAttribute("redirectUrl", webRequest.getDescription(false));
        return "exceptionpage";
    }
}
Gyanendra
  • 21
  • 2
  • According to Spring's documentation, `By default, the methods in an @ControllerAdvice apply globally to all controllers`. However, it seems like you might have other configs that are affecting this. Can you try to add basePackages and see if it would solve the problem? `@ControllerAdvice(basePackages = {"com.whatever.your.controller.package"})` – skryvets Jan 16 '21 at 16:12
  • 1
    Didn't worked. only the code to handle a Parent Exception class is working. code to handle child Exception class doesn't work if I implement the code to handle its Parent. even after specifying the base package in @ControllerAdvice. – Gyanendra Jan 18 '21 at 09:16

1 Answers1

0

(if this question is still unresolved)

In my case, the problem was, that the Exception for what I created the ExceptionHandler was just the cause of another Exception, so that's why the @ExceptionHandler(Exception.class) caught it instead.

So maybe you could check if the Exception is actually of that class in the debugger.

tkalvin
  • 71
  • 1
  • 8