简体   繁体   中英

How do Spring Boot @ExceptionHandlers intercept exceptions

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

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(ie 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.

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM