TIL) ResponseEntity์ Custom Exception
๐ ์ค๋์ ๋ด์ฉ์ ๋ฆฌ
์๊ณ ๋ฆฌ์ฆ ์คํฐ๋ 6์ผ์ฐจ
ResponseEntity
ResponseEntity๋ ์คํ๋ง์์ ์ ๊ณตํ๋ HttpEntity๋ฅผ ์์๋ฐ์ ๊ตฌํํ ํด๋์ค์ด๋ค.
์๋ต์ ๋ํ๋ด๋ ํด๋์ค๋ก, ์๋ต ๋ณธ๋ฌธ, ์ํ์ฝ๋, ํค๋๋ฅผ ํฌํจํ๊ณ ์๋ค.
ResponseEntity๋ฅผ ์ฌ์ฉํ๋ฉด ์๋ต์ ์์ธํ๊ฒ ์ ์ดํ ์ ์์ด์ ํด๋ผ์ด์ธํธ์ ์๋ฒ๊ฐ์ ํต์ ์ ์ ์ฐํ๊ฒ ์ฒ๋ฆฌํ ์ ์๋ค.
Custom Exception
ํ์ฌ ์ฝ๋์์๋ ๊ฒ์๊ธ์ด ์กด์ฌํ์ง ์์ ๋์ ๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ ๋ ์์ธ์ํฉ์ ์ฒ๋ฆฌํ๊ณ ์๋๋ฐ, ๋ชจ๋ 500์ผ๋ก ํด๋ผ์ด์ธํธ์๊ฒ ์ ๋ฌ๋๋ค. ์๋ฏธ์๋ ๋ฐ์ดํฐ๋ ๊ฐ์ด ์ ๋ฌ๋๋ ์ํฉ์ด๋ค.
๋ฐ์ํ ์์ธ๋ฅผ ์ ์ ํ๊ฒ ์ ๋ฌํ๊ธฐ ์ํด์ ์ปค์คํ ์์ธ๋ฅผ ๋ง๋ค์ด ๋ณด์!
1. ErrorCode enum ์์ฑ
@AllArgsConstructor
@Getter
public enum ErrorCode {
INVALID_AUTH(HttpStatus.UNAUTHORIZED, "๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค."),
BOARD_NOT_FOUND(HttpStatus.NOT_FOUND, "๊ฒ์๊ธ์ด ์กด์ฌํ์ง ์์ต๋๋ค."),
;
private final HttpStatus httpStatus;
private final String message;
}
2. Exception, ExceptionHandler ์ถ๊ฐ
@AllArgsConstructor
@Getter
public class CustomException extends RuntimeException{
ErrorCode errorCode;
}
@ControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(CustomException.class)
public ResponseEntity<ErrorResponseEntity> handleCustomException(CustomException e){
return ErrorResponseEntity.toResponseEntity(e.getErrorCode());
}
}
@ControllerAdvice
- ์ฌ๋ฌ ์ปจํธ๋กค๋ฌ์์ ๋ฐ์ํ ์ ์๋ ์์ธ๋ฅผ ์ผ๊ด์ฒ๋ฆฌ ํ๋ค.
@ExceptionHandler
- @ControllerAdvice๊ฐ ์ ์ฉ๋ ํด๋์ค ๋ด๋ถ์์ ํน์ ์์ธ ํ์ ์ ์ฒ๋ฆฌํ๋ ๋ฉ์๋๋ฅผ ์ ์ํ ์ ์๋ค.
3. ErrorResponseEntity ์ถ๊ฐ
@Data
@Builder
public class ErrorResponseEntity {
private int status;
private String name;
private String message;
public static ResponseEntity<ErrorResponseEntity> toResponseEntity(ErrorCode e){
return ResponseEntity
.status(e.getHttpStatus())
.body(ErrorResponseEntity.builder()
.status(e.getHttpStatus().value())
.name(e.name())
.message(e.getMessage())
.build());
}
}
4. ์ฌ์ฉ
private Board getBoardById(long id) {
return boardRepository.findById(id).orElseThrow(() -> new CustomException(StatusEnum.BOARD_NOT_FOUND));
}
// ๋น๋ฐ ๋ฒํธ ์ผ์น ์ฌ๋ถ ํ์ธ
private void passwordCheck(Board board, String inputPassword) {
if (!board.getPassword().equals(inputPassword)) {
throw new CustomException(StatusEnum.PASSWORD_NOT_MATCHED);
}
}
5. ๊น๋!
๐ ์ค๋์ ๋ง๋ฌด๋ฆฌ
์คํ๋ง ๊ณผ์ ๋ฅผ ๋ง๋ฌด๋ฆฌํ๊ณ ์ ์ถํ๋ค. ์์ง๋ Exception์ ์ฒ๋ฆฌํ๋๊ฑด ๋ฏ์ค๋ค. ๋ฏ์ค์๋ ์ฝ๋๋ค์ด ์ธ์ ๊ฐ ์ต์ํด์ก๋ ๊ฒ์ฒ๋ผ Exception ์ฒ๋ฆฌ๋ ํ๋ค๋ณด๋ฉด ์ต์ํด์ง๋ ๋ ์ด ์ค์ง ์์๊น? ๋ฌผ๋ก ๊ทธ๋ฐ ์๊ฐ์ ๋๋ฌํ๋ ค๋ฉด ๋์ฑ๋ ์ด์ฌํ ํด์ผ๊ฒ ์ง!