슈퍼코딩/주특기(JAVA)

2024.06.03(월) 슈퍼코딩 신입연수원 10주차 Day 1 후기 - 예외 처리, AOP

곰돌이볼 2024. 6. 3. 23:08
  • 강의
    • 100강(스프링부트와 문서화와 로깅 남기기) ~ 102강(스프링부트와 JPA)

예외 처리


  • HTTP status code
    • 500 : 최대한 지양
    • 400 : Bad Request
    • 403 : Forbidden
    • 404 : Not Found
    • 406 : Not Acceptable
  • HTTP status 500 발생 이유
    • 특정 상황 예외 발생했지만 아무도 처리하지 않은 경우
  • 예외 처리의 핵심
    • 외부 전파 예외
      • controller layer까지 전파 → 클라이언트에게 예외 전달
      • controller : HTTP error 코드 + 메세지 응답 전달
      • @RestContollerAdvice 사용
    • 내부 예외
      • 내부 다른 Default 값으로 치환
      • 상위 내부  layer 전파 후 처리
  • @RestControllerAdvice
    • 특징
      • web layer
      • 전역적인 exception 처리
      • @ResponseStatus : HTTP Status 설정
      • @ExceptionHandler : 에러 클래스 ex) @ExceptionHandler(NotFoundException.class)
    • 장점
      • 반복적인 코드 감소
      • try-catch문 생략으로 가독성 향상
public class NotFoundException extends RuntimeException {

    public NotFoundException(String message) {
        super(message);
    }
}
@RestControllerAdvice
public class ExceptionControllerAdvice {
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NotFoundException.class)
    public String handleNotFoundException(NotFoundException e) {
        return e.getMessage();
    }
}

AOP


  • AOP = Ascpect Oriented Programming, 관점 지향형 프로그래밍
  • 공통적인 코드들의 모듈화
    • 예외 처리 : ex) ControllerAdvice
    • 로깅
    • 보안
    • ex) 트랜잭션 : 공통 데이터 원자화
  • 어드 바이스(advice) : 구현된 모듈화
  • 어드바이스가 필요한 로직에 침투하여 사용됨