개발을 하다 보면 에러를 리턴 해야 할 때가 있다.
보통 http status를 400번대와 error code, error data등을 리턴하게 된다.
하지만 기존 설계에서는 표준에 맞지 않게 리턴하고 있었다.
error code 관련해서 구조화 작업을 진행 했다.
public interface ErrorCode {
HttpStatus retrieveHttpStatus();
String retrieveErrorCode();
String retrieveErrorMessage();
}
public class ErrorCodeField {
private final HttpStatus httpStatus;
private final String errorCode;
protected final String errorMessage;
}
public enum UserErrorCodeV2 implements ErrorCode {
USER_INFO_NOT_FOUND(BAD_REQUEST, "user info is not exist");
private final ErrorCodeField errorCodeField;
UserErrorCodeV2(HttpStatus httpStatus, String errorMessage) {
errorCodeField = new ErrorCodeField(httpStatus, errorMessage);
}
@Override
public HttpStatus retrieveHttpStatus() {
return errorCodeField.getHttpStatus();
}
@Override
public String retrieveErrorCode() {
return isNull(errorCodeField.getErrorCode()) ? name() : errorCodeField.getErrorCode();
}
@Override
public String retrieveErrorMessage() {
return errorCodeField.getErrorMessage();
}
}
public class ErrorBodyDto {
private String errorCode;
private String errorMessage;
private Object errorData;
public ErrorBodyDto(String errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public static ErrorBodyDto of(String errorCode, String errorMessage) {
return ErrorBodyDto.builder()
.errorCode(errorCode)
.errorMessage(errorMessage)
.build();
}
}
public class ResponseErrorException extends RuntimeException {
private HttpStatus httpStatus;
private ErrorBodyDto errorBody;
private ResponseErrorException(HttpStatus httpStatus, ErrorBodyDto errorBody) {
this.httpStatus = httpStatus;
this.errorBody = errorBody;
}
private ResponseErrorException(ErrorCode errorCode, Object errorData) {
super(createResponseErrorMessage(errorCode));
this.httpStatus = errorCode.retrieveHttpStatus();
this.errorBody = ErrorBodyDto.builder()
.errorCode(errorCode.retrieveErrorCode())
.errorMessage(errorCode.retrieveErrorMessage())
.errorData(errorData)
.build();
}
public static ResponseErrorException of(ErrorCode errorCode){
return new ResponseErrorException(errorCode, null);
}
public static ResponseErrorException of(ErrorCode errorCode, Object errorData){
return new ResponseErrorException(errorCode, errorData);
}
}