Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.
Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

@RestControllerAdvice
public class YourControllerAdvice {

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

}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading