- 시작하게 된 계기 및 다짐 😮
이번 코드스테이츠의 백엔드 엔지니어링 개발자 부트캠프
에 참여하게 되면서 현직개발자 분들의 빠른 성장을 위한 조언 중 자신만의 블로그를 이용하여 배운 것 들을 정리하는게 많은 도움이 된다 하여 시작하게 되었다.
- 학습 목표 😮
목표 | 결과 |
---|---|
서비스 계층에서 의도적으로 예외를 던지는 방법과 상황을 이해 | O |
사용자 정의 예외(Custom Exception) 생성 | O |
@RestControllerAdvice 애너테이션을 사용해서 예외 | O |
서비스 계층에서 던져진 예외를 API 계층에서 처리 | O |
- 정리😮
0. 에러 메세지로 부터 특정 정보를 받는 메서드들
1. 체크 예외(Checked Exception)과 언체크 예외(Unchecked Exception)
2. 개발자가 의도적으로 던지는(throw) 예외
3. 의도적인 예외 던지기/받기(throw/catch)
[예제 Code]
@Service
public class MemberService {
public Member findMember(long memberId) {
// TODO should business logic
// (1)
//throw new RuntimeException("Not found member");
throw new BusinessLogicException(ExceptionCode.MEMBER_NOT_FOUND);
}
}
@RestControllerAdvice
public class GlobalExceptionAdvice {
// (1)
@ExceptionHandler
//@ResponseStatus(HttpStatus.NOT_FOUND) ==> status가 에러에 따라 바뀌기 때문에 ResponseEnitity를 사용
//public ErrorResponse handleResourceNotFoundException(RuntimeException e) {
// System.out.println(e.getMessage());
public ErrorResponse handlerBusinessLogicException(BusinessLogicException e){
System.out.println(e.getExceptionCode().getStatus());
System.out.println(e.getMessage());
//return null;
return new ResponseEntity<>(HttpStatus.valueOf(e.getExceptionCode());
}
}
4. 사용자 정의 예외(Custom Exception) 사용
[예제 Code]
public enum ExceptionCode {
MEMBER_NOT_FOUND(404, "Member Not Found");
@Getter
private int status;
@Getter
private String message;
ExceptionCode(int status, String message) {
this.status = status;
this.message = message;
}
}
public class BusinessLogicException extends RuntimeException {
@Getter
private ExceptionCode exceptionCode;
public BusinessLogicException(ExceptionCode exceptionCode) {
super(exceptionCode.getMessage());
this.exceptionCode = exceptionCode;
}
}
Extra
throw와 throws 차이점
MethodArgumentNotValidException
ConstraintViolationException
@Slf4j
- 피드백 😮
비지니스 로직을 처리하는 와중 발생하는 에러들은 체크/언체크 예외가 있는데 '체크 예외'의 경우 발생한 에러를 처리해주는 예외고 '언체크 예외'의 경우 딱히 처리할 필요가 없는 에러들이다.
개발자가 원하는 결과값이 나오지 않을시 의도적으로 예외를 던져서 이를 처리할 수 있음
사용자가 직접 enum클래스를 이용하여 특정 예외(ex. Exception)를 커스텀해서 처리할 수 있음
- 앞으로 해야 될 것 😮