TIL 35 : 예외처리 복습
자바에서 Exception은 다시 2가지로 나뉩니다.
- Checked Exception
- UnChecked Exception
Checked Exception 은 반드시 try-catch나 상위 메소드로 throws 처리를 해야 하는 예외를 말합니다. 처리를 하지 않고 컴파일을 시도하면 오류가 발생하며 실패 합니다.
UnChecked Exception 은 별도 Exception을 처리하지 않아도 컴파일이 가능하고 프로그램 실행도 정상적으로 됩니다.
장점 | 단점 | |
Checked Exception | - 예외 처리 강제 → 코드 안정성 향상 - 예외 발생 가능성을 명확히 문서화 |
- 가독성이 떨어짐 → 코드 생산성 하락 - 불필요한 예외 처리로 코드 복잡성 증가 |
Unchecked Exception | - 단순하고 가독성 높은 코드 작성 가능 - 필요할 때만 예외 처리 |
- 예외를 누락할 가능성이 있음 - 시스템의 신뢰도 하락 |
Spring Boot의 예외처리
- try-catch (Spring은 자바 기반이므로 자바와 동일한 try-catch를 씁니다)
- @ExceptionHandler, @ControllerAdvice
- @Valid, @Validated
- 그 외 유용한 유효성 어노테이션
@ExceptionHandler, @ControllerAdvice는 둘 다 예외를 핸들링하는 어노테이션입니다. 차이점은 다음과 같습니다.
- @ExceptionHandler : 하나의 Controller 만 예외 핸들링
- @ControllerAdvice : 모든 Controller에서 발생하는 예외 핸들링
/* @ExceptionHandler */
@RestController
public class SampleController {
@GetMapping("/test")
public String test() {
throw new IllegalArgumentException("Invalid input!");
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
return ResponseEntity.badRequest().body("Error: " + ex.getMessage());
}
}
@RestController
public class DemoController {
@GetMapping("/demo")
public String demo() {
throw new IllegalArgumentException("Invalid input!");
}
}
/* @ControllerAdvice */
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
return ResponseEntity.badRequest().body("Global Error: " + ex.getMessage());
}
}
@RestController
public class SampleController {
@GetMapping("/test")
public String test() {
throw new IllegalArgumentException("Invalid input!");
}
}
@RestController
public class DemoController {
@GetMapping("/demo")
public String demo() {
throw new IllegalArgumentException("Invalid input!");
}
}
참고 자료 : https://tecoble.techcourse.co.kr/post/2023-05-03-ExceptionHandler-ControllerAdvice/
ExceptionHandler와 ControllerAdvice를 알아보자
콘솔 애플리케이션을 구현할 때, 우리는 예외를 핸들링하기 위해 try / catch…
tecoble.techcourse.co.kr
@Valid, @Validated
데이터를 검증하기 위한 어노테이션.
활성화 하기 위해서는 아래 의존성을 추가 해야 합니다.
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation
implementation 'org.springframework.boot:spring-boot-starter-validation:3.3.5'
@Valid | @Validated | |
특징 | JSR-303 자바 표준 검증 어노테이션 | Spring Boot 제공 어노테이션 |
발생 예외 | MethodArgumentNotValidException | ConstraintViolationException |
적용 계층 | 기본 : Controller 별도 설정시 : Service, Bean 등 사용 가능 |
Controller + 다른 계층 |
그룹 기반 검증 | X | O |
@Valid 예시
@RestController
public class UserController {
@PostMapping("/user")
public ResponseEntity<String> createUser(@RequestBody @Valid UserDto userDto){
return ResponseEntity.ok("User is valid!");
}
}
@Getter
public class UserDto {
private Long id;
@Min(20)
private Long age;
@Override
public String toString() {
return "UserDto{id=" + id + ", age=" + age + '}';
}
}
@Validated 예시
@Validated
@RestController
public class ValidatedController {
@PostMapping("/test-validated/number")
public String testValid(@Min(10) Integer number, @RequestBody @Valid UserDto userDto) {
return number + " : " + userDto.toString();
}
}
@Getter
public class UserDto {
private Long id;
@Min(20)
private Long age;
@Override
public String toString() {
return "UserDto{id=" + id + ", age=" + age + '}';
}
}
참고 자료 : https://doubleyoo.tistory.com/48
[Spring] @Valid와 @Validated를 이용한 유효성 검증
참고: @Valid와 @Validated를 이용한 유효성 검증의 동작 원리 및 사용법 예시 Validation 올바르지 않은 데이터를 걸러내고, 보안을 유지하기 위해 데이터 검증은 여러 계층에 걸쳐서 적용된다. 클라이
doubleyoo.tistory.com
그 외 유용한 유효성 검증 어노테이션
# | 어노테이션 | 설명 | 대상 |
1 | @Positive | 양수만 허용. 0은 제외 | 숫자형 타입 |
2 | @PositiveOrZero | 0 포함 양수만 허용 | 숫자형 타입 |
3 | @Min(1), @Max(100) | 최소, 최대값 제한 | 숫자형 타입 |
4 | @Size(max = 50) | 문자열 길이 제한 | 문자열 |
5 | 이메일 형식 체크 | 문자열 |
참고 자료 : https://better-tomorrow-than-today.tistory.com/98
@NonNull, @Nonnull, @NotNull, @NotEmpty, @NotBlank 비교
1. 정리하게된 배경초기 도메인 필드의 유효성을 검증하고자, 아래와 같이 @NonNull을 이용해서 구현했다. 초기 프로젝트 환경에서 validation 의존성이 추가되지 않아서, Spring 에서 제공되는 @NonNull
better-tomorrow-than-today.tistory.com