Reputation: 15
Lets say we have a post mapping for example that creates and returns a person object and its request body provides a first and last name that are both primary keys for some database. If either value is null then an exception is thrown.
Assuming we have another controller set up to handle the exception and intercept it with the @controlleradvice and @exceptionhandler annotations and a method that returns a ResponseEntity How does it actually intercept the exception and why does the return type of the handler not have to match the return type of the post method that threw it. Sorry if it is a silly question, i just cant seem to grasp it. I would like to understand whats happening behind the scenes.
I understand what the annotations do and hiw we specify what exception to handle, I just dont understand the how
Upvotes: 1
Views: 72
Reputation: 4604
ExceptionHandler
is pointcut aspects in spring's aspect oriented programming terminologies.
As per pointcut doc:
Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name)
We define type of exception in ExceptionHandler
annotation(i.e. Exception.class
etc) . Jointpoint aspect in this case is handling exception thrown by advice's (here ControllerAdvice
) method.
When exception occurred in advice's method, you are supposed to throw that exception & your spring advice intercept that exception & pass control to pointcut which then matches exception type & do its handling.
Regarding method signature of ExceptionHandler
, doc says its flexible & hence it is not strict to return type of post method you defined.
Upvotes: 1