I have a controller class with REST methods that can throw various exceptions. I have decided to handle these exceptions in a separate class using the @ControllerAdvice and @ExceptionHandler for my handler methods. However, I have the problem, that my REST methods use an annotation from another library. This library catches an exception that my REST method throws as well. Now that I am handling the exceptions globally and not via try/catch in the REST method directly, my exception is always caught by the other library and not by my own handler method. Apparently, that other method in the library I am using wins due to the annotation. How can I bind the exception handling to my own class to prevent it from being caught by anyone else?
My REST method:
@SomeLibraryAnnotation
@PostMapping(path = "/add", consumes = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity< ? > addItem(@RequestHeader HttpHeaders headers, @RequestBody MyDTO myDTO)
throws UnsupportedOperationException {
doSomethingWith(myDTO);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
My Exception Handler class:
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(UnsupportedOperationException.class)
public ResponseEntity<?> handleUnsupportedOperationException(UnsupportedOperationException e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(e.getMessage());
}
}
As the library method also catches the UnsupportedOperationException, it wins due to the @SomeLibraryAnnotation and the exception is never handled in my handler class.