◈ 백준 - ★재귀★ (2606*,1012*)
■ 바이러스(2606번)
■ 유기농배추(1012번)
◈ Restful Web Service
■ HTTP Status 제어하기
User user =service.findOne(id);
if (user == null) { // 데이터가 null이라면
throw new UserNotFoundException(String.format("ID[%s not found", id)); //
}
만약 user값이 null값으로 나온다면 UserNotFoundException 클래스에 예외를 던지고
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
RuntimeException을 상속받아 message를 저장.
● @ResponseStatus는 예외 발생시 발생한 오류 대신 (HttpStatus.Not_Found)에 해당하는 404번 오류를 내보낸다.
@RestController
@ControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND);
}
하나씩 살펴보자!
@RestController
@ControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler
● @ControllerAdvice : 스프링 프레임워크에서 예외처리와 관련된 전역적인 설정을 제공한다. 여러 컨트롤러에서 발생하는 예외를 한곳에서 처리하고자 할때 사용!
● ResponseEntityExceptionHandler : @ControllerAdvice를 사용하여 예외처리할때 상속받는다.
- Exception ex, 는 예외 객체를 받고, WebRequest는 현재 요청에 대한 정보를 받아 request.getDescription에 넣어준다.
getDescription(boolean includeClientInfo) : includeClientInfo를 true로 설정하면 클라이언트의 세부정보를 포함하여
설명을 반환 false일 경우 세부정보를 포함하지 않은 요청에 대한 설명을 반환한다.
● @ExceptionHandler(Exception.class) : Exception 예외 발생시 발동
++) Controller, RestController에만 적용이 가능(@Service x)
@ExceptionHandler를 등록한 Controller에만 적용 가능(다른 Controller에서 예외처리 불가)
▶ ▶ But, @ControllerAdvice와 함께 사용한다면 전역설정이 가능해짐!
● ExceptionResponse : 예외가 발생했을 때 클라이언트에게 전달될 응답의 구조를 정의한다.
예외의 타임스탬프, 메시지 및 요청에 대한 설명을 불러오기가 가능!
public class ExceptionResponse {
private Date timestamp;
private String message;
private String details;
}
ExceptionResponse 클래스를 만들어서 불러올 변수들을 저장
■ Validations 유효성 검사
implementation 'org.springframework.boot:spring-boot-starter-validation'
build.gradle에 dependencies 추가
// UserController
@PostMapping("/users")
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
User savedUser = service.save(user);
user의 정보를 저장할때 유효성 검사(@Valid)를 하고자 한다.
// bean.User
@Size(min =2, message = "Name은 2글자 이상 입력해주세요")
private String name;
@Past(message="등록일은 미래 날짜 입력X")
private Date joinDate;
@Size, @Past 등을 이용하여 조건을 설정한다. (이외에 @NotNull, @NotBlank, @Email, @Min, @Max 등등이 있다.)
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), "Validation Failed", ex.getBindingResult().toString());
// ex.getMessage()
return new ResponseEntity<>(exceptionResponse, HttpStatus.BAD_REQUEST);
}
해당 조건에 부합시 나타나는 message를 나타내기 위하여 ResponseEntityExceptionHandler의 MethodArgumentNotValidException 예외가 발생되었을때 호출되는 handleMethodArgumentNotValid 클래스를 @Override.하여 사용한다.
User 클래스에서 조건을 설정할때 작성한 message를 보여주고싶을때는 ex.getMessage() 하거나
혹은 원하는 메시지를 입력하여 보여주기가 가능하다.
● @Override 하기 전.
@Override 진행.
출처 : https://www.inflearn.com/course/spring-boot-restful-web-services/dashboard
'Study Record' 카테고리의 다른 글
24/02/14 - Swagger, MappingJacksonValue, HATEOUS (1) | 2024.02.15 |
---|---|
24/02/13 SQL Lv2, User mode/Karnel mode, Switch (0) | 2024.02.13 |
24/02/08 Network(TCP/IP, UDP) SQL LV1, HashMap (0) | 2024.02.09 |
24/02/07 Stack, @RestController, @ResponseEntity (0) | 2024.02.08 |
Entity, VO, DTO의 차이점 (0) | 2024.01.24 |