Skip to content

Commit

Permalink
Merge pull request #11 from STUDIO-EYE/feat/EPIC-136]-user
Browse files Browse the repository at this point in the history
[Feat] GlobalExceptionHandler 구현하여 이메일검증
  • Loading branch information
ibaesuyeon authored Jun 6, 2024
2 parents f3a68db + 92b43af commit 0bddf49
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand Down Expand Up @@ -59,7 +60,7 @@ public ResponseEntity<UserResponse> findUserResponseByUserId(@PathVariable("user
return ResponseEntity.ok().body(userResponse);
} catch (BusinessLogicException e) {
ExceptionCode exceptionCode = e.getExceptionCode();
int status = exceptionCode.getStatus();
HttpStatus status = exceptionCode.getStatus();
String message = exceptionCode.getMessage();
return ResponseEntity.status(status).body(new UserResponse(message));
}
Expand All @@ -72,7 +73,7 @@ public ResponseEntity<UserResponse> findUserResponseByEmail(@PathVariable String
return ResponseEntity.ok().body(userResponse);
} catch (BusinessLogicException e) {
ExceptionCode exceptionCode = e.getExceptionCode();
int status = exceptionCode.getStatus();
HttpStatus status = exceptionCode.getStatus();
String message = exceptionCode.getMessage();
return ResponseEntity.status(status).body(new UserResponse(message));
}
Expand Down
59 changes: 59 additions & 0 deletions src/main/java/com/example/UserService/dto/ApiResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.example.UserService.dto;

import com.example.UserService.exception.ExceptionCode;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;

@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ApiResponse<T> {

// API 상태 코드
private int code;

// API 상태
private HttpStatus status;

// API 응답 메시지
private String message;

// API 응답 데이터
private T data;

private ApiResponse(HttpStatus status, String message, T data) {
this.code = status.value();
this.status = status;
this.message = message;
this.data = data;
}

public static <T> ApiResponse<T> of(HttpStatus status, String message, T data) {
return new ApiResponse<>(status, message, data);
}

public static <T> ApiResponse<T> of(HttpStatus status, T data) {
return of(status, status.name(), data);
}

public static <T> ApiResponse<T> ok(T data) {
return of(HttpStatus.OK, data);
}

public static <T> ApiResponse<T> ok(String message) {
return of(HttpStatus.OK, message, null);
}

public static <T> ApiResponse<T> ok(String message, T data) {
return of(HttpStatus.OK, message, data);
}

public static <T> ApiResponse<T> withError(ExceptionCode exceptionCode, T data) {
return new ApiResponse<>(exceptionCode.getStatus(), exceptionCode.getMessage(), data);
}

public static <T> ApiResponse<T> withError(ExceptionCode exceptionCode) {
return withError(exceptionCode, null);
}
}
39 changes: 18 additions & 21 deletions src/main/java/com/example/UserService/exception/ExceptionCode.java
Original file line number Diff line number Diff line change
@@ -1,29 +1,26 @@
package com.example.UserService.exception;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;

@Getter
@RequiredArgsConstructor
public enum ExceptionCode {
MEMBER_NOT_FOUND(404, "회원을 찾을 수 없습니다"),
RESOURCE_NOT_FOUND(404, "리소스를 찾을 수 없습니다"),
BAD_REQUEST(400, "잘못된 요청입니다"),
UNAUTHORIZED(401, "인증되지 않았습니다"),
FORBIDDEN(403, "접근이 금지되었습니다"),
INVALID_INPUT(422, "유효하지 않은 입력입니다"),
INTERNAL_SERVER_ERROR(500, "내부 서버 오류입니다"),
MEMBER_EXISTS(409, "이미 존재하는 회원입니다"),
NO_SUCH_ALGORITHM(500, "존재하지 않는 알고리즘입니다"),
UNABLE_TO_SEND_EMAIL(500, "이메일을 전송할 수 없습니다"),
TOKEN_IS_NOT_SAME(401, "액세스 토큰과 리프레시 토큰이 일치하지 않습니다"),
HEADER_REFRESH_TOKEN_NOT_EXISTS(400, "요청 헤더에 리프레시 토큰이 누락되었습니다");
MEMBER_NOT_FOUND(HttpStatus.NOT_FOUND, "회원을 찾을 수 없습니다"),
RESOURCE_NOT_FOUND(HttpStatus.NOT_FOUND, "리소스를 찾을 수 없습니다"),
BAD_REQUEST(HttpStatus.BAD_REQUEST, "잘못된 요청입니다"),
UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "인증되지 않았습니다"),
FORBIDDEN(HttpStatus.FORBIDDEN, "접근이 금지되었습니다"),
INVALID_INPUT(HttpStatus.BAD_REQUEST, "유효하지 않은 입력입니다"),
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "내부 서버 오류입니다"),
MEMBER_EXISTS(HttpStatus.CONFLICT, "이미 존재하는 회원입니다"),
NO_SUCH_ALGORITHM(HttpStatus.INTERNAL_SERVER_ERROR, "존재하지 않는 알고리즘입니다"),
UNABLE_TO_SEND_EMAIL(HttpStatus.INTERNAL_SERVER_ERROR, "이메일을 전송할 수 없습니다"),
TOKEN_IS_NOT_SAME(HttpStatus.UNAUTHORIZED, "액세스 토큰과 리프레시 토큰이 일치하지 않습니다"),
HEADER_REFRESH_TOKEN_NOT_EXISTS(HttpStatus.BAD_REQUEST, "요청 헤더에 리프레시 토큰이 누락되었습니다");

@Getter
private int status;
private final HttpStatus status;
private final String message;

@Getter
private String message;

ExceptionCode(int status, String message) {
this.status = status;
this.message = message;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.example.UserService.exception;

import com.example.UserService.dto.ApiResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(BlogAPIException.class)
public ApiResponse<?> handleBlogAPIException(BlogAPIException e) {
return ApiResponse.withError(ExceptionCode.MEMBER_EXISTS);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
import com.example.UserService.dto.UserResponse;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {

Optional<UserEntity> findByEmail(String email);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand Down Expand Up @@ -80,7 +81,7 @@ public String register(RequestUser requestUser) {

// add check for email exists in database
if(userRepository.existsByEmail(requestUser.getEmail())){
throw new BlogAPIException(HttpStatus.BAD_REQUEST, "Email is already exists!.");
throw new BlogAPIException(HttpStatus.BAD_REQUEST, "Email is already exists!");
}

ModelMapper mapper = new ModelMapper();
Expand All @@ -91,7 +92,7 @@ public String register(RequestUser requestUser) {
userEntity.setCreatedAt(LocalDate.now());
userRepository.save(userEntity);

return "User registered successfully!.";
return "User registered successfully!";
}

@Override
Expand Down

0 comments on commit 0bddf49

Please sign in to comment.