J L
J L

Reputation: 987

Avoid code duplication Spring Boot Controller

I have the following RestController (Spring boot 2.0.4) with several methods that follow the same structure of execute. They may point out to different url or be annotated with @GetMapping instead of @PostMapping:

@RestController
public class Controller {
    private final DataAccessLayer dal;

    @PostMapping("myUrl_1") execute(@RequestBody String param) {

        try {
            ... 
        } catch (CustomException e) {
            ...
        } catch (CustomException_2 e_2) {
            ...
        } finally {
            ...
        }
    }
    ...
}

The only difference is the param usage and the dal usage.

My question is, how can I avoid code duplication in catch and finally clauses??

Upvotes: 2

Views: 703

Answers (2)

Pragya
Pragya

Reputation: 198

You can use @ControllerAdvice and @ExceptionHandler.

@ControllerAdvice : By default @ControllerAdvice will apply to all classes that use the @Controller annotation. If you wanted this to be more specific then you can do so by writing some properties like @ControllerAdvice("my.org.package")

@ExceptionHandler : Using @ControllerAdvice along with @ExceptionHandler provides global error handling. You can write the annotations @ExceptionHandler(IllegalArgumentException.class) which will handle all the exception for IllegalArgumentException.

For more details you can refer this :

Upvotes: 3

dai
dai

Reputation: 1075

use @ControllerAdvice and @ExceptionHandler. link

Upvotes: 0

Related Questions