Skip to content

Commit

Permalink
[refac] BaseResponse, ExceptionHandler 수정 (#32)
Browse files Browse the repository at this point in the history
* [refac] create interface for code

* [refac] refactor exception and common api response

* [feat] create response advice

* [refac] fix typo in UserErrorCode.java

* [refac] change Hankki response creation logic

* [refac] delete duplicated BaseTimeEntity.java

* [refac] fix HankkiResponse.java as api spec

* [refac] fix unappropriate error message while validating refreshtoken

* [refac] change typo in ResponseAdvice.java
  • Loading branch information
Parkjyun authored Jul 9, 2024
1 parent a33777c commit 7edf277
Show file tree
Hide file tree
Showing 33 changed files with 299 additions and 240 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,41 @@
package org.hankki.hankkiserver.api.advice;

import lombok.extern.slf4j.Slf4j;
import org.hankki.hankkiserver.api.dto.HankkiResponse;
import org.hankki.hankkiserver.common.code.BusinessErrorCode;
import org.hankki.hankkiserver.common.exception.BadRequestException;
import org.hankki.hankkiserver.common.exception.NotFoundException;
import org.hankki.hankkiserver.common.exception.UnauthorizedException;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

@ExceptionHandler(BadRequestException.class)
public HankkiResponse<Void> handleBadRequestException(BadRequestException e) {
log.error("handleBadRequestException() in GlobalExceptionHandler throw BadRequestException : {}", e.getMessage());
return HankkiResponse.fail(e.getErrorCode());
}

@ExceptionHandler(UnauthorizedException.class)
public HankkiResponse<Void> handleUnauthorizedException(UnauthorizedException e) {
log.error("handleUnauthorizedException() in GlobalExceptionHandler throw UnauthorizedException : {}", e.getMessage());
return HankkiResponse.fail(e.getErrorCode());
}

@ExceptionHandler(NotFoundException.class)
public HankkiResponse<Void> handleEntityNotFoundException(NotFoundException e) {
log.error("handleEntityNotFoundException() in GlobalExceptionHandler throw EntityNotFoundException : {}", e.getMessage());
return HankkiResponse.fail(e.getErrorCode());
}

@ExceptionHandler(Exception.class)
public HankkiResponse<Void> handleException(Exception e) {
log.error("handleException() in GlobalExceptionHandler throw Exception : {}", e.getMessage());
return HankkiResponse.fail(BusinessErrorCode.INTERNAL_SERVER_ERROR);

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package org.hankki.hankkiserver.api.advice;

import org.hankki.hankkiserver.api.dto.HankkiResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = "org.hankki.hankkiserver.api")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return returnType.getParameterType() == HankkiResponse.class;
}

@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (returnType.getParameterType() == HankkiResponse.class) {
HttpStatus status = HttpStatus.valueOf(((HankkiResponse<?>) body).getCode());
response.setStatusCode(status);
}
return body;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@
import jakarta.annotation.Nullable;
import lombok.RequiredArgsConstructor;
import org.hankki.hankkiserver.auth.UserId;
import org.hankki.hankkiserver.api.dto.ApiResponse;
import org.hankki.hankkiserver.api.dto.BaseResponse;
import org.hankki.hankkiserver.common.code.SuccessCode;
import org.hankki.hankkiserver.api.dto.HankkiResponse;
import org.hankki.hankkiserver.common.code.CommonSuccessCode;
import org.hankki.hankkiserver.api.auth.service.AuthService;
import org.hankki.hankkiserver.api.auth.controller.request.UserLoginRequest;
import org.hankki.hankkiserver.api.auth.service.response.UserLoginResponse;
import org.hankki.hankkiserver.api.auth.service.response.UserReissueResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
Expand All @@ -22,32 +20,32 @@ public class AuthController {
private final AuthService authService;

@PostMapping("/auth/login")
public ResponseEntity<BaseResponse<?>> login(
public HankkiResponse<UserLoginResponse> login(
@RequestHeader(HttpHeaders.AUTHORIZATION) final String token,
@RequestBody final UserLoginRequest request) {
final UserLoginResponse response = authService.login(token, request);
return ApiResponse.success(SuccessCode.OK, response);
return HankkiResponse.success(CommonSuccessCode.OK, response);
}

@PatchMapping("/auth/logout")
public ResponseEntity<BaseResponse<?>> signOut(
public HankkiResponse<Void> signOut(
@UserId final Long userId) {
authService.logOut(userId);
return ApiResponse.success(SuccessCode.OK);
return HankkiResponse.success(CommonSuccessCode.OK);
}

@DeleteMapping("/auth/withdraw")
public ResponseEntity<BaseResponse<?>> withdraw(
public HankkiResponse<Void> withdraw(
@UserId final Long userId,
@Nullable @RequestHeader("X-Apple-Code") final String code){
authService.withdraw(userId,code);
return ApiResponse.success(SuccessCode.NO_CONTENT);
return HankkiResponse.success(CommonSuccessCode.NO_CONTENT);
}

@PostMapping("/auth/reissue")
public ResponseEntity<BaseResponse<?>> reissue(
public HankkiResponse<UserReissueResponse> reissue(
@RequestHeader(HttpHeaders.AUTHORIZATION) final String refreshToken) {
final UserReissueResponse response = authService.reissue(refreshToken);
return ApiResponse.success(SuccessCode.OK, response);
return HankkiResponse.success(CommonSuccessCode.OK, response);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
import org.hankki.hankkiserver.auth.jwt.JwtProvider;
import org.hankki.hankkiserver.auth.jwt.JwtValidator;
import org.hankki.hankkiserver.auth.jwt.Token;
import org.hankki.hankkiserver.common.code.ErrorCode;
import org.hankki.hankkiserver.common.code.AuthErrorCode;
import org.hankki.hankkiserver.domain.user.model.User;
import org.hankki.hankkiserver.domain.user.model.UserInfo;
import org.hankki.hankkiserver.domain.user.model.Platform;
import org.hankki.hankkiserver.common.exception.InvalidValueException;
import org.hankki.hankkiserver.common.exception.BadRequestException;
import org.hankki.hankkiserver.common.exception.UnauthorizedException;
import org.hankki.hankkiserver.external.openfeign.apple.AppleOAuthProvider;
import org.hankki.hankkiserver.external.openfeign.dto.SocialInfoDto;
Expand All @@ -19,8 +19,6 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

import static org.hankki.hankkiserver.domain.user.model.MemberStatus.ACTIVE;
import static org.hankki.hankkiserver.domain.user.model.Platform.APPLE;
import static org.hankki.hankkiserver.domain.user.model.Platform.KAKAO;
Expand Down Expand Up @@ -65,7 +63,7 @@ public void withdraw(final long userId, final String code) {
String refreshToken = appleOAuthProvider.getAppleToken(code);
appleOAuthProvider.requestRevoke(refreshToken);
} catch (Exception e) {
throw new InvalidValueException(ErrorCode.APPLE_REVOKE_FAILED);
throw new BadRequestException(AuthErrorCode.APPLE_REVOKE_FAILED);
}
}
user.softDelete();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package org.hankki.hankkiserver.api.auth.service;

import lombok.RequiredArgsConstructor;
import org.hankki.hankkiserver.common.code.ErrorCode;
import org.hankki.hankkiserver.common.exception.EntityNotFoundException;
import org.hankki.hankkiserver.common.code.UserErrorCode;
import org.hankki.hankkiserver.common.exception.NotFoundException;
import org.hankki.hankkiserver.domain.user.model.Platform;
import org.hankki.hankkiserver.domain.user.model.User;
import org.hankki.hankkiserver.domain.user.repository.UserRepository;
Expand All @@ -21,7 +21,7 @@ public class UserFinder {

public User getUser(final long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new EntityNotFoundException(ErrorCode.USER_NOT_FOUND));
.orElseThrow(() -> new NotFoundException(UserErrorCode.USER_NOT_FOUND));
}

public boolean isRegisteredUser(final Platform platform, final SocialInfoDto socialInfo) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package org.hankki.hankkiserver.api.auth.service;

import lombok.RequiredArgsConstructor;
import org.hankki.hankkiserver.common.code.ErrorCode;
import org.hankki.hankkiserver.common.exception.EntityNotFoundException;
import org.hankki.hankkiserver.common.code.UserErrorCode;
import org.hankki.hankkiserver.common.exception.NotFoundException;
import org.hankki.hankkiserver.domain.user.model.UserInfo;
import org.hankki.hankkiserver.domain.user.repository.UserInfoRepository;
import org.springframework.stereotype.Component;
Expand All @@ -15,6 +15,6 @@ public class UserInfoFinder {

public UserInfo getUserInfo(final long userId) {
return userInfoRepository.findByUserId(userId)
.orElseThrow(() -> new EntityNotFoundException(ErrorCode.USER_INFO_NOT_FOUND));
.orElseThrow(() -> new NotFoundException(UserErrorCode.USER_INFO_NOT_FOUND));
}
}
23 changes: 0 additions & 23 deletions src/main/java/org/hankki/hankkiserver/api/dto/ApiResponse.java

This file was deleted.

42 changes: 0 additions & 42 deletions src/main/java/org/hankki/hankkiserver/api/dto/BaseResponse.java

This file was deleted.

30 changes: 30 additions & 0 deletions src/main/java/org/hankki/hankkiserver/api/dto/HankkiResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package org.hankki.hankkiserver.api.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
import org.hankki.hankkiserver.common.code.ErrorCode;
import org.hankki.hankkiserver.common.code.SuccessCode;

@Getter
@Builder(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class HankkiResponse<T> {

private final int code;
private final String message;
@JsonInclude(value = JsonInclude.Include.NON_NULL)
private T data;

public static <T> HankkiResponse<T> success(SuccessCode success) {
return new HankkiResponse<>(success.getHttpStatus().value(), success.getMessage());
}

public static <T> HankkiResponse<T> success(SuccessCode success, T data) {
return new HankkiResponse<>(success.getHttpStatus().value(), success.getMessage(), data);
}

public static <T> HankkiResponse<T> fail(ErrorCode error) {
return new HankkiResponse<>(error.getHttpStatus().value(), error.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.hankki.hankkiserver.api.dto.BaseResponse;
import org.hankki.hankkiserver.common.code.ErrorCode;
import org.hankki.hankkiserver.api.dto.HankkiResponse;
import org.hankki.hankkiserver.common.code.AuthErrorCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
Expand All @@ -28,17 +28,17 @@ public void commence(
}

private void handleException(HttpServletResponse response) throws IOException {
setResponse(response, HttpStatus.UNAUTHORIZED, ErrorCode.UNAUTHORIZED);
setResponse(response, HttpStatus.UNAUTHORIZED, AuthErrorCode.UNAUTHORIZED);
}

private void setResponse(
HttpServletResponse response,
HttpStatus httpStatus,
ErrorCode errorCode) throws IOException {
AuthErrorCode authErrorCode) throws IOException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("utf-8");
response.setStatus(httpStatus.value());
PrintWriter writer = response.getWriter();
writer.write(objectMapper.writeValueAsString(BaseResponse.of(errorCode)));
writer.write(objectMapper.writeValueAsString(HankkiResponse.fail(authErrorCode)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.hankki.hankkiserver.api.dto.BaseResponse;
import org.hankki.hankkiserver.api.dto.HankkiResponse;
import org.hankki.hankkiserver.common.code.AuthErrorCode;
import org.hankki.hankkiserver.common.code.ErrorCode;
import org.hankki.hankkiserver.common.exception.UnauthorizedException;
import org.springframework.http.HttpStatus;
Expand Down Expand Up @@ -36,25 +37,25 @@ private void handleUnauthorizedException(
HttpServletResponse response,
Exception e) throws IOException {
UnauthorizedException ue = (UnauthorizedException) e;
ErrorCode errorCode = ue.getErrorCode();
HttpStatus httpStatus = errorCode.getHttpStatus();
setResponse(response, httpStatus, errorCode);
ErrorCode authErrorCode = ue.getErrorCode();
HttpStatus httpStatus = authErrorCode.getHttpStatus();
setResponse(response, httpStatus, authErrorCode);
}

private void handleException(
HttpServletResponse response,
Exception e) throws IOException {
setResponse(response, HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.INTERNAL_SERVER_ERROR);
setResponse(response, HttpStatus.INTERNAL_SERVER_ERROR, AuthErrorCode.INTERNAL_SERVER_ERROR);
}

private void setResponse(
HttpServletResponse response,
HttpStatus httpStatus,
ErrorCode errorCode) throws IOException {
ErrorCode authErrorCode) throws IOException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("utf-8");
response.setStatus(httpStatus.value());
PrintWriter writer = response.getWriter();
writer.write(objectMapper.writeValueAsString(BaseResponse.of(errorCode)));
writer.write(objectMapper.writeValueAsString(HankkiResponse.fail(authErrorCode)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import org.hankki.hankkiserver.auth.UserAuthentication;
import org.hankki.hankkiserver.auth.jwt.JwtProvider;
import org.hankki.hankkiserver.auth.jwt.JwtValidator;
import org.hankki.hankkiserver.common.code.ErrorCode;
import org.hankki.hankkiserver.common.code.AuthErrorCode;
import org.hankki.hankkiserver.common.exception.UnauthorizedException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
Expand Down Expand Up @@ -44,7 +44,7 @@ private String getAccessToken(HttpServletRequest request) {
if (StringUtils.hasText(accessToken) && accessToken.startsWith(BEARER)) {
return accessToken.substring(BEARER.length());
}
throw new UnauthorizedException(ErrorCode.INVALID_ACCESS_TOKEN);
throw new UnauthorizedException(AuthErrorCode.INVALID_ACCESS_TOKEN);
}

private void doAuthentication(
Expand Down
Loading

0 comments on commit 7edf277

Please sign in to comment.