ControllerAdvice exception handling based on URL matching

In my application I have two type of urls – /secure and /unsecure.
For any exception arising from /secure/** URLs I want to do a certain type of exception handling and provide detailed error response and for /unsecure/** I want to provide a generic response entity. So basically want to have two ControllerAdvice classes for these two different type of URL endpoints. Is it possible to have multiple controller advice that can do this so that I can define different behaviours for the same exception in these two controller advices.

I have many controllers with /secure/** URL and many with /unsecure/** endpoints and some controllers are mix of both /secure/** and /unsecure/** endpoints.

>Solution :

In the @RestControllerAdvice Annotation you can specify the packages it should do the work for. So if you separate the /secure/** and /unsecure/** controllers clearly you can have two advices.

For the mixed ones you could implement logic based on the servlet path in your @RestControllerAdvice. This is not exactly the two different advices you ask for but maybe a solution that works:

public class YourControllerAdvice {

  public ResponseEntity<Object> handleYourException(HttpServletRequest request, YourException e) {
    if(request.getServletPath().contains("/unsecure/")) {
      //return your generic ResponseEntity
    } else {
      //return your detailed Errormessage


Leave a Reply