ErrorCode
@Getter
@AllArgsConstructor
public enum LettripErrorCode {
DUPLICATED_EMAIL("이미 해당 Email로 가입된 계정이 존재합니다."),
WRONG_PASSWORD("비밀번호가 일치하지 않습니다."),
INTERNAL_SERVER_ERROR("서버에 오류가 발생했습니다."),
INVALID_REQUEST("잘못된 요청입니다.");
private final String message;
}
- 일단 회원가입/ 로그인 기능을 구현하면서 필요할 에러 코드들로 구성해보았다.
LettripException
@Getter
public class LettripException extends RuntimeException{
private final LettripErrorCode lettripErrorCode;
private final String detailMessage;
public LettripException(LettripErrorCode lettripErrorCode) {
super(lettripErrorCode.getMessage());
this.lettripErrorCode = lettripErrorCode;
this.detailMessage = lettripErrorCode.getMessage();
}
public LettripException(LettripErrorCode lettripErrorCode, String detailMessage) {
super(detailMessage);
this.lettripErrorCode = lettripErrorCode;
this.detailMessage = detailMessage;
}
}
LettripErrorResponse
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class LettripErrorResponse {
private LettripErrorCode errorCode;
private String errorMessage;
}
- 오류가 발생했을 때 클라이언트 측에 보내줄 Response를 담고 있는 객체이다.
LettripExceptionHandler
@Slf4j
@RestControllerAdvice
public class LettripExceptionHandler {
@ResponseStatus(value = HttpStatus.CONFLICT)
@ExceptionHandler(LettripException.class)
public LettripErrorResponse handleException(
LettripException e, HttpServletRequest request
) {
log.error("errorCode: {}, url: {}, message: {}",
e.getLettripErrorCode(), request.getRequestURI(), e.getDetailMessage());
return LettripErrorResponse.builder()
.errorCode(e.getLettripErrorCode())
.errorMessage(e.getDetailMessage())
.build();
}
@ExceptionHandler(value = {
HttpRequestMethodNotSupportedException.class,
MethodArgumentNotValidException.class
})
public LettripErrorResponse handleBadRequest(
Exception e, HttpServletRequest request
) {
log.error("url: {}, message: {}",
request.getRequestURI(), e.getMessage());
return LettripErrorResponse.builder()
.errorCode(LettripErrorCode.INVALID_REQUEST)
.errorMessage((LettripErrorCode.INVALID_REQUEST.getMessage()))
.build();
}
@ExceptionHandler(Exception.class)
public LettripErrorResponse handleException(
Exception e, HttpServletRequest request
) {
log.error("url: {}, message: {}",
request.getRequestURI(), e.getMessage());
return LettripErrorResponse.builder()
.errorCode(LettripErrorCode.INTERNAL_SERVER_ERROR)
.errorMessage((LettripErrorCode.INTERNAL_SERVER_ERROR.getMessage()))
.build();
}
}
@RestControllerAdvice 를 통해, 모든 RestController에서 발생하는 Exception들이 이 Handler에 의해 처리된다.
- 직접 커스텀한
LettripException은 handleException 메서드, HttpRequestMethodNotSupportedException,MethodArgumentNotValidException는 handleBadRequest 메서드,
그 이외의 모든 Exception들은 마지막 handleException 메서드에 의해 처리된다.