@ExceptionHandler


해당 어노테이션을 사용하면 특정 예외를 잡을 메서드를 정의해줄 수 있다.

코드로 살펴보자. 아래는 일반적인 컨트롤러 구성이다.

@AllArgsConstructor
@RestController
public class DemoController {

    DemoService demoService;

    @PostMapping("/demo")
    public ResponseBase demo(@RequestBody RequestBase request) {
        try {
            return ResponseBase.of(demoService.update(request));
        } catch (Exception e) {
            return ResponseBase.of(null);
        }
    }
}

 

위의 코드를 @ExceptionHandler를 사용하면 아래와 같이 바꿔줄 수 있다.

@AllArgsConstructor
@RestController
public class DemoController {

    DemoService demoService;

    @PostMapping("/demo")
    public ResponseBase demo(@RequestBody RequestBase request) {
        return ResponseBase.of(demoService.update(request));
    }
    
    @ExceptionHandler(Exception.class)
    protected ResponseBase handleException(Exception e) {
        return ResponseBase.of(null);
    }
}

 

컨트롤러에 특정 예외를 던지는 진입 메서드가 많으면 많을수록 코드량을 상당히 줄일 수 있게 된다.

@ExceptionHandler의 특징으로는

  1. Controller, RestController에서만 사용할 수 있다. (Service단에서는 사용 불가능)
  2. 리턴 타입을 자유롭게 지정해줄 수 있다.
  3. 해당 메서드를 정의한 컨트롤러에서만 적용된다. (타 컨트롤러에서는 적용안됨)

 

 

 

@ControllerAdvice


Advice는 AOP에서 사용되는 용어인데 컨트롤러를 기준으로 실행 전, 중, 후에 특정 로직을 끼워넣고싶을 때 사용한다.

@ControllerAdvice
public class DemoAdvice {

    @ExceptionHandler(Exception.class)
    public ResponseBase demo() {
        return ResponseBase.of(null);
    }
}

 

 

 

참고자료


[1] https://jeong-pro.tistory.com/195