- 이렇게 ApiResult로 정의해서 반환하는 방식은 openAPI처럼 되게 형식적인 api일 때 이렇게 사용 보통함
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.springframework.http.HttpStatus; public class ApiResult<T> { private final boolean success; private final T response; private final ApiError error; private ApiResult(boolean success, T response, ApiError error) { this.success = success; this.response = response; this.error = error; } public static <T> ApiResult<T> OK(T response) { return new ApiResult<>(true, response, null); } public static ApiResult<?> ERROR(Throwable throwable, HttpStatus status) { return new ApiResult<>(false, null, new ApiError(throwable, status)); } public static ApiResult<?> ERROR(String errorMessage, HttpStatus status) { return new ApiResult<>(false, null, new ApiError(errorMessage, status)); } public boolean isSuccess() { return success; } public ApiError getError() { return error; } public T getResponse() { return response; } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .append("success", success) .append("response", response) .append("error", error) .toString(); } }
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.springframework.http.HttpStatus; public class ApiError { private final String message; private final int status; ApiError(Throwable throwable, HttpStatus status) { this(throwable.getMessage(), status); } ApiError(String message, HttpStatus status) { this.message = message; this.status = status.value(); } public String getMessage() { return message; } public int getStatus() { return status; } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .append("message", message) .append("status", status) .toString(); } }
컨트롤러에서 사용하는 예시
@GetMapping(path = "user/{userId}/post/list") public ApiResult<List<PostDto>> posts(@PathVariable Long userId) { return OK( postService.findAll(Id.of(User.class, userId)).stream() .map(PostDto::new) .collect(toList()) ); }
- 모든 컨트롤러에서 반환값으로 ApiResult에 제네릭으로 써서 공통 부분을 풀어내기도 한다