Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REFACTOR] 커스텀 에러 코드 적용 #144

Merged
merged 7 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.tiki.server.auth.controller;

import com.tiki.server.auth.controller.docs.AuthControllerDocs;
import com.tiki.server.auth.dto.request.SignInRequest;
import com.tiki.server.auth.dto.response.ReissueGetResponse;
import com.tiki.server.auth.dto.response.SignInGetResponse;
Expand All @@ -19,17 +20,19 @@
@RestController
@RequiredArgsConstructor
@RequestMapping("api/v1/auth")
public class AuthController {
public class AuthController implements AuthControllerDocs {

private final AuthService authService;

@Override
@PostMapping("/sign-in")
public ResponseEntity<SuccessResponse<SignInGetResponse>> signIn(@RequestBody SignInRequest request) {
val response = authService.signIn(request);
return ResponseEntity.created(UriGenerator.getUri("/"))
.body(SuccessResponse.success(SUCCESS_SIGN_IN.getMessage(), response));
}

@Override
@GetMapping("/reissue")
public ResponseEntity<SuccessResponse<ReissueGetResponse>> reissue(HttpServletRequest httpServletRequest) {
val response = authService.reissueToken(httpServletRequest);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ public interface AuthControllerDocs {
description = "서버 내부 오류",
content = @Content(schema = @Schema(implementation = ErrorResponse.class)))}
)
ResponseEntity<SuccessResponse<SignInGetResponse>> login(
HttpServletResponse httpServletResponse,
@RequestBody SignInRequest request);
ResponseEntity<SuccessResponse<SignInGetResponse>> signIn(@RequestBody SignInRequest request);

@Operation(
summary = "엑세스 토큰 재발급",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package com.tiki.server.auth.exception.handler;

import static com.tiki.server.auth.message.ErrorCode.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiki.server.auth.message.ErrorCode;
import com.tiki.server.common.dto.ErrorResponse;
import com.tiki.server.common.dto.ErrorCodeResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -30,14 +31,15 @@ public void commence(
AuthenticationException authException
) throws IOException {
log.info("[AuthenticationEntryPoint] " + authException.getMessage());
setResponse(response, ErrorCode.UNAUTHENTICATED.getMessage());
setResponse(response);
}

private void setResponse(HttpServletResponse response, String errorMessage) throws IOException {
private void setResponse(HttpServletResponse response) throws IOException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
val writer = response.getWriter();
writer.write(objectMapper.writeValueAsString(ErrorResponse.of(errorMessage)));
writer.write(objectMapper.writeValueAsString(
ErrorCodeResponse.of(UNAUTHENTICATED.getCode(), UNAUTHENTICATED.getMessage())));
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
package com.tiki.server.auth.filter;

import static com.tiki.server.auth.message.ErrorCode.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiki.server.auth.exception.AuthException;
import com.tiki.server.auth.message.ErrorCode;
import com.tiki.server.common.dto.ErrorResponse;
import com.tiki.server.common.dto.ErrorCodeResponse;
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
Expand All @@ -35,30 +36,19 @@ protected void doFilterInternal(
filterChain.doFilter(request, response);
} catch (AuthException e) {
log.info("[ExceptionHandlerFilter] - AuthException : " + e);
handleAuthException(response, e);
setResponse(response, e.getErrorCode());
} catch (Exception e) {
log.info("[ExceptionHandlerFilter] - UncaughtException : " + e);
handleUncaughtException(response);
setResponse(response, UNCAUGHT_EXCEPTION);
}
}

private void handleAuthException(HttpServletResponse response, AuthException e) throws IOException {
val errorMessage = e.getErrorCode().getMessage();
val httpStatus = e.getErrorCode().getHttpStatus();
setResponse(response, httpStatus, errorMessage);
}

private void handleUncaughtException(HttpServletResponse response) throws IOException {
val uncaughtException = ErrorCode.UNCAUGHT_EXCEPTION;
setResponse(response, uncaughtException.getHttpStatus(), uncaughtException.getMessage());
}

private void setResponse(HttpServletResponse response, HttpStatus httpStatus, String errorMessage)
private void setResponse(HttpServletResponse response, ErrorCode errorCode)
throws IOException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.setStatus(httpStatus.value());
response.setStatus(errorCode.getHttpStatus().value());
val writer = response.getWriter();
writer.write(objectMapper.writeValueAsString(ErrorResponse.of(errorMessage)));
writer.write(objectMapper.writeValueAsString(ErrorCodeResponse.of(errorCode.getCode(), errorCode.getMessage())));
}
}

This file was deleted.

22 changes: 12 additions & 10 deletions src/main/java/com/tiki/server/auth/message/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,23 @@
@AllArgsConstructor
public enum ErrorCode {

/* 400 INTERNAL_SERVER_ERROR : 잘못된 요청입니다. */
UNCAUGHT_EXCEPTION(BAD_REQUEST, "예상치 못한 오류입니다."),
/* 400 BAD REQUEST : 잘못된 요청 */
UNCAUGHT_EXCEPTION(BAD_REQUEST, 40001, "예상치 못한 오류가 발생했습니다."),

/* 401 UNAUTHORIZED : 인증 없음 */
UNAUTHENTICATED(UNAUTHORIZED, "인증과정중 오류가 발생했습니다"),
UNMATCHED_TOKEN(UNAUTHORIZED, "토큰이 일치하지 않습니다."),
INVALID_JWT_TOKEN(UNAUTHORIZED, "잘못된 토큰 형식입니다."),
EXPIRED_JWT_TOKEN(UNAUTHORIZED, "만료된 토큰입니다."),
EMPTY_JWT(UNAUTHORIZED, "빈 토큰입니다."),
UNAUTHENTICATED(UNAUTHORIZED, 40101, "인증 과정 중 오류가 발생했습니다"),
UNMATCHED_TOKEN(UNAUTHORIZED, 40102, "토큰이 일치하지 않습니다."),
INVALID_JWT_TOKEN(UNAUTHORIZED, 40103, "잘못된 토큰 형식입니다."),
EXPIRED_JWT_TOKEN(UNAUTHORIZED, 40104, "만료된 토큰입니다."),
EMPTY_JWT(UNAUTHORIZED, 40105, "빈 토큰입니다."),

/* 403 FORBIDDEN : 인가 없음 */
UNAUTHORIZED_USER(FORBIDDEN, "권한이 없는 사용자입니다."),
/* 403 FORBIDDEN : 권한 없음 */
UNAUTHORIZED_USER(FORBIDDEN, 40301, "권한이 없는 사용자입니다."),

UNCAUGHT_SERVER_EXCEPTION(INTERNAL_SERVER_ERROR,"처리되지 않은 에러ㅜ(서버한테 물어보삼)");
/* 500 INTERNAL_SERVER_ERROR : 서버 내부 오류 발생 */
UNCAUGHT_SERVER_EXCEPTION(INTERNAL_SERVER_ERROR, 500, "서버 내부에서 오류가 발생했습니다.");

private final HttpStatus httpStatus;
private final int code;
private final String message;
}
22 changes: 22 additions & 0 deletions src/main/java/com/tiki/server/common/dto/ErrorCodeResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.tiki.server.common.dto;

import static lombok.AccessLevel.PRIVATE;

import lombok.Builder;
import lombok.NonNull;

@Builder(access = PRIVATE)
public record ErrorCodeResponse(
boolean success,
int code,
@NonNull String message
) implements BaseResponse {

public static ErrorCodeResponse of(int code, String message) {
return ErrorCodeResponse.builder()
.success(false)
.code(code)
.message(message)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.tiki.server.common.handler;

import com.tiki.server.auth.exception.AuthException;
import com.tiki.server.common.dto.ErrorCodeResponse;
import com.tiki.server.mail.exception.MailException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
Expand Down Expand Up @@ -77,7 +78,8 @@ public ResponseEntity<BaseResponse> MailException(MailException exception) {
public ResponseEntity<BaseResponse> AuthException(AuthException exception) {
log.error(exception.getMessage());
val errorCode = exception.getErrorCode();
return ResponseEntity.status(errorCode.getHttpStatus()).body(ErrorResponse.of(errorCode.getMessage()));
return ResponseEntity.status(errorCode.getHttpStatus()).body(
ErrorCodeResponse.of(errorCode.getCode(), errorCode.getMessage()));
}

@ExceptionHandler(Exception.class)
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/com/tiki/server/document/message/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ public enum ErrorCode {
/* 400 BAD_REQUEST : 잘못된 요청 */
INVALID_TYPE(BAD_REQUEST, "유효한 타입이 아닙니다."),

/* 404 NOT_FOUND : 자원을 찾을 수 없음 */
INVALID_DOCUMENT(NOT_FOUND, "유효하지 않은 문서입니다."),

/* 403 FORBIDDEN : 권한 없음 */
INVALID_AUTHORIZATION(FORBIDDEN, "문서에 대한 권한이 없습니다.");
INVALID_AUTHORIZATION(FORBIDDEN, "문서에 대한 권한이 없습니다."),

/* 404 NOT_FOUND : 자원을 찾을 수 없음 */
INVALID_DOCUMENT(NOT_FOUND, "유효하지 않은 문서입니다.");

private final HttpStatus httpStatus;
private final String message;
Expand Down
7 changes: 3 additions & 4 deletions src/main/java/com/tiki/server/external/message/ErrorCode.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.tiki.server.external.message;

import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;

import org.springframework.http.HttpStatus;
Expand All @@ -12,9 +11,9 @@
@AllArgsConstructor
public enum ErrorCode {

/* 500 INTERNAL_SERVER_ERROR : 서버 에러 */
PRESIGNED_URL_GET_ERROR(INTERNAL_SERVER_ERROR, "S3 PRESIGNED URL 불러오기 실패"),
FILE_DELETE_ERROR(INTERNAL_SERVER_ERROR, "S3 버킷의 파일 삭제 실패");
/* 500 INTERNAL_SERVER_ERROR : 서버 내부 오류 발생 */
PRESIGNED_URL_GET_ERROR(INTERNAL_SERVER_ERROR, "S3 PRESIGNED URL 불러오기에 실패했습니다."),
FILE_DELETE_ERROR(INTERNAL_SERVER_ERROR, "S3 버킷의 파일 삭제에 실패했습니다.");

private final HttpStatus httpStatus;
private final String message;
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/tiki/server/mail/message/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@
@AllArgsConstructor
public enum ErrorCode {

/* 403 BAD REQUEST: 인증 거부 */
/* 403 FORBIDDEN : 권한 없음 */
INVALID_MATCHED(FORBIDDEN, "인증 정보가 일치하지 않습니다."),

/* 404 NOT FOUND: 요청 리소스를 찾을 수 없음 */
/* 404 NOT_FOUND : 자원을 찾을 수 없음 */
INVALID_REQUEST(NOT_FOUND, "인증 정보가 존재하지 않습니다."),

/* 500 INTERNAL_SERVER_ERROR 서버 내부 오류 발생 */
/* 500 INTERNAL_SERVER_ERROR : 서버 내부 오류 발생 */
MESSAGE_HELPER_ERROR(INTERNAL_SERVER_ERROR,"메세지를 설정할 수 없습니다.");

private final HttpStatus httpStatus;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
@AllArgsConstructor
public enum ErrorCode {

/* 400 BAD REQUEST: 잘못된 요청 */
/* 400 BAD REQUEST : 잘못된 요청 */
UNMATCHED_PASSWORD(BAD_REQUEST, "비밀번호가 일치하지 않습니다."),
INVALID_EMAIL(BAD_REQUEST, "잘못된 이메일 형식입니다."),

Expand Down
Loading