이것저것 해보기🌼

Validation, Exception 처리하기 본문

BE/Spring Boot

Validation, Exception 처리하기

realtree 2021. 7. 5. 18:32

 

- Gradle Dependencies

1
implementation 'org.springframework.boot:spring-boot-starter-validation'
cs

 

 

1. Validation

변수 선언시 다양하게 validation 사용가능

 

1
2
3
4
5
6
7
    @NotEmpty
    @Size(min=1, max=100)
    private String name;
 
    @Min(1)
    @NotNull
    private Integer age;
cs

 

 

*bean validation spec 참조

https://beanvalidation.org/2.0-jsr380/

 

Jakarta Bean Validation - Bean Validation 2.0 (JSR 380)

Bean Validation 2.0 focused on the following topics: support for validating container elements by annotating type arguments of parameterized types e.g. List<@Positive Integer> positiveNumbers. This also includes: more flexible cascaded validation of contai

beanvalidation.org

 

 

2. Exception Handler

@ControllerAdvice : global 예외처리 및 특정 package/controller 예외처리

@ExceptionHandler : 특정 controller의 예외처리

 

 

- Global Controller Advide 작성 예시

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package advice;
 
 
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
@RestControllerAdvice()
public class GlobalControllerAdvice {
 
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity exception(Exception e){
 
        System.out.println(e.getClass().getName());
        System.out.println("--------------");
        System.out.println(e.getLocalizedMessage());
        System.out.println("--------------");
 
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("");
    }
 
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity methodArgumentNotValidException(MethodArgumentNotValidException e){
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
    }
}
 
cs

 

만약, @RestControllerAdvice(basePackageClasses = ApiController.class) 라고 지정한다면,

ApiController 라는 클래스에 해당하는 에러만 위 로직을 타게 만들수 있다.

'BE > Spring Boot' 카테고리의 다른 글

[JUnit] CRUD 테스트코드 작성하기  (0) 2021.07.06
[Open API] 네이버 Open API 사용하기  (0) 2021.07.06
Annotation 정리  (0) 2021.07.05
[AOP] 메소드 로그 찍기, Decode/Encode 하기  (0) 2021.07.05
Spring 핵심  (0) 2021.07.05