diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..55d79e4 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9ea06b8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### OS ### +.DS_Store +Thumbs.db + diff --git a/README.md b/README.md index d0553e6..2ecd8a7 100644 --- a/README.md +++ b/README.md @@ -1 +1,142 @@ # common + +Michelet MSA 전체 서비스가 공유하는 **공통 모듈(Java Library)**. + +--- + +## 포함 내용 + +| 패키지 | 구성 요소 | 설명 | +|---|---|---| +| `com.michelet.common.response` | `ApiResponse` (record) | 모든 REST 응답의 통일 포맷. traceId 자동 삽입 | +| `com.michelet.common.exception` | `ErrorCode` (interface) | 도메인별 에러 코드 enum이 구현 | +| `com.michelet.common.exception` | `BusinessException` | 비즈니스 규칙 위반 예외 (RuntimeException) | +| `com.michelet.common.exception` | `GlobalExceptionHandler` | `@RestControllerAdvice` 전역 예외 처리기 | +| `com.michelet.common.entity` | `BaseEntity` | JPA Auditing + Soft Delete 베이스 엔티티 | +| `com.michelet.common.config` | `CommonAutoConfiguration` | common 모듈 자동 설정 진입점 | +| `com.michelet.common.config` | `JpaAuditingConfig` | `@EnableJpaAuditing` 활성화 | + +--- + +## 기술 스택 + +- **JDK**: 17 +- **Spring Boot**: 3.5.14 +- **Build Tool**: Gradle (java-library plugin) +- **GroupId**: `com.michelet` + +--- + +## 서비스에서 사용하기 + +common 은 **Spring Boot Auto-Configuration** 으로 등록되므로, +의존만 걸면 `GlobalExceptionHandler` 와 `@EnableJpaAuditing` 이 자동 적용된다. +**별도의 `scanBasePackages` 설정은 필요 없다.** + +### 1. 의존성 추가 + +각 서비스의 `build.gradle`: + +```gradle +repositories { + mavenCentral() + maven { url 'https://jitpack.io' } +} + +dependencies { + implementation 'com.github.Miche-Let:common:main-SNAPSHOT' +} +``` + +> `` 는 깃 태그(`v0.0.1` 등), 브랜치(`main-SNAPSHOT`), 또는 커밋 해시. + +### 2. `AuditorAware` Bean 등록 (필수) + +`BaseEntity` 의 `createdBy` / `updatedBy` 를 채우려면 각 서비스가 **현재 로그인 사용자의 UUID** 를 제공해야 한다. common 은 인증 문맥을 알 수 없으므로 이 Bean 은 서비스에서 반드시 등록. + +```java +@Configuration +public class AuditorConfig { + + @Bean + public AuditorAware auditorAware() { + return () -> { + // 예시: SecurityContext / MDC / 요청 헤더 등에서 userId 추출 + String userId = MDC.get("userId"); + return userId != null + ? Optional.of(UUID.fromString(userId)) + : Optional.empty(); + }; + } +} +``` + +> ⚠️ 이 Bean 이 없거나 `Optional.empty()` 를 반환하면 +> `BaseEntity.createdBy` 의 `NOT NULL` 제약에 걸려 INSERT 가 실패한다. + +--- + +## 사용 예시 + +**성공 응답** +```java +@GetMapping("/{id}") +public ApiResponse getUser(@PathVariable UUID id) { + return ApiResponse.success(userService.get(id)); +} +``` + +**비즈니스 예외** +```java +public enum UserErrorCode implements ErrorCode { + USER_NOT_FOUND("USER_001", "유저를 찾을 수 없습니다.", 404); + // ... getCode(), getMessage(), getHttpStatus() 구현 +} + +throw new BusinessException(UserErrorCode.USER_NOT_FOUND); +``` + +**엔티티 상속** +```java +@Entity +public class Waiting extends BaseEntity { + @Id @GeneratedValue private UUID id; + // createdAt, createdBy, updatedAt, updatedBy, deletedAt, deletedBy 자동 제공 +} +``` + + +## 로컬 빌드 + +```bash +./gradlew clean build +./gradlew publishToMavenLocal # 로컬에서 다른 서비스가 바로 쓰고 싶을 때 +``` + +--- + +## common 패키지 구조 + +```text +common/ +├── build.gradle +├── settings.gradle +└── src/ + └── main/ + ├── java/com/michelet/common/ + │ ├── config/ + │ │ ├── CommonAutoConfiguration.java + │ │ └── JpaAuditingConfig.java + │ ├── entity/ + │ │ └── BaseEntity.java + │ ├── exception/ + │ │ ├── BusinessException.java + │ │ ├── ErrorCode.java + │ │ └── GlobalExceptionHandler.java + │ └── response/ + │ ├── ApiResponse.java + │ └── SuccessCode.java + └── resources/ + └── META-INF/spring/ + └── org.springframework.boot.autoconfigure.AutoConfiguration.imports +``` diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..c68c9bd --- /dev/null +++ b/build.gradle @@ -0,0 +1,60 @@ +plugins { + id 'java-library' + id 'org.springframework.boot' version '3.5.14' apply false + id 'io.spring.dependency-management' version '1.1.6' +} + +group = 'com.michelet' +version = '0.0.1-SNAPSHOT' + + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +// 라이브러리이므로 Spring Boot 실행 파일(bootJar)은 비활성화, 일반 jar 만 생성 +tasks.named('jar') { + enabled = true + archiveClassifier = '' +} + +repositories { + mavenCentral() +} + +dependencyManagement { + imports { + mavenBom "org.springframework.boot:spring-boot-dependencies:3.5.14" + } +} + +dependencies { + // 공통 모듈이 제공하는 기능들에 필요한 최소 의존성 + // api 로 노출해서 서비스가 별도 선언 없이 바로 쓸 수 있게 함 + api 'org.springframework.boot:spring-boot-starter-web' + api 'org.springframework.boot:spring-boot-starter-validation' + api 'org.springframework.boot:spring-boot-starter-data-jpa' + + // Lombok + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + // Tracing 정보를 로그(MDC)로 연결 , 내부 구현용 + implementation 'io.micrometer:micrometer-tracing-bridge-brave' + + // Test + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +test { + useJUnitPlatform() +} + +// Javadoc 경고 완화 (record 등) +javadoc { + options.addStringOption('Xdoclint:none', '-quiet') +} + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..8bdaf60 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2a84e18 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..ef07e01 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..48fe92d --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'common' diff --git a/src/main/java/com/michelet/common/config/CommonAutoConfiguration.java b/src/main/java/com/michelet/common/config/CommonAutoConfiguration.java new file mode 100644 index 0000000..0c8e2af --- /dev/null +++ b/src/main/java/com/michelet/common/config/CommonAutoConfiguration.java @@ -0,0 +1,18 @@ +package com.michelet.common.config; + +import com.michelet.common.exception.GlobalExceptionHandler; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.context.annotation.Import; + +/** + * common-module 자동 설정 진입점. + * + */ +@AutoConfiguration +@Import({ + JpaAuditingConfig.class, + GlobalExceptionHandler.class +}) +public class CommonAutoConfiguration { +} + diff --git a/src/main/java/com/michelet/common/config/JpaAuditingConfig.java b/src/main/java/com/michelet/common/config/JpaAuditingConfig.java new file mode 100644 index 0000000..8dd8bbd --- /dev/null +++ b/src/main/java/com/michelet/common/config/JpaAuditingConfig.java @@ -0,0 +1,16 @@ +package com.michelet.common.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +/** + * JPA Auditing 활성화 설정. + * 각 서비스에서 별도 @EnableJpaAuditing 을 달 필요 없이, common-module 의존성만으로 동작한다. + * + * 각 서비스는 AuditorAware Bean 을 반드시 등록해야 한다 + * (common 은 누가 로그인 중인지 알 수 없기 때문). + */ +@Configuration +@EnableJpaAuditing(auditorAwareRef = "auditorAware") +public class JpaAuditingConfig { +} diff --git a/src/main/java/com/michelet/common/entity/BaseEntity.java b/src/main/java/com/michelet/common/entity/BaseEntity.java new file mode 100644 index 0000000..bf6b4f9 --- /dev/null +++ b/src/main/java/com/michelet/common/entity/BaseEntity.java @@ -0,0 +1,52 @@ +package com.michelet.common.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; +import java.util.UUID; + +@Getter +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public abstract class BaseEntity { + + @CreatedDate + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt; + + @CreatedBy + @Column(name = "created_by", nullable = false, updatable = false, columnDefinition = "uuid") + private UUID createdBy; + + @LastModifiedDate + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @LastModifiedBy + @Column(name = "updated_by", columnDefinition = "uuid") + private UUID updatedBy; + + @Column(name = "deleted_at") + private LocalDateTime deletedAt; + + @Column(name = "deleted_by", columnDefinition = "uuid") + private UUID deletedBy; + + /** Soft Delete 처리. 상속 엔티티에서 비즈니스 메서드로 호출한다. */ + public void softDelete(UUID deletedBy) { + this.deletedAt = LocalDateTime.now(); + this.deletedBy = deletedBy; + } + + public boolean isDeleted() { + return this.deletedAt != null; + } +} diff --git a/src/main/java/com/michelet/common/exception/BusinessException.java b/src/main/java/com/michelet/common/exception/BusinessException.java new file mode 100644 index 0000000..ed95d63 --- /dev/null +++ b/src/main/java/com/michelet/common/exception/BusinessException.java @@ -0,0 +1,22 @@ +package com.michelet.common.exception; + +import lombok.Getter; + +// 도메인 비즈니스 규칙 위반 시 던지는 예외 +// GlobalExceptionHandler가 잡아서 ApiResponse.error(...)로 변환 +@Getter +public class BusinessException extends RuntimeException { + + private final String errorCode; + private final int httpStatus; + + public BusinessException(ErrorCode errorCode) { + this(errorCode, null); + } + + public BusinessException(ErrorCode errorCode, Throwable cause) { + super(java.util.Objects.requireNonNull(errorCode, "errorCode must not be null").getMessage(), cause); + this.errorCode = errorCode.getCode(); + this.httpStatus = errorCode.getHttpStatus(); + } +} diff --git a/src/main/java/com/michelet/common/exception/ErrorCode.java b/src/main/java/com/michelet/common/exception/ErrorCode.java new file mode 100644 index 0000000..743e365 --- /dev/null +++ b/src/main/java/com/michelet/common/exception/ErrorCode.java @@ -0,0 +1,9 @@ +package com.michelet.common.exception; + +// 각 도메인별 에러 코드 enum이 이 인터페이스를 구현 +// 예: UserErrorCode implements ErrorCode +public interface ErrorCode { + String getCode(); // "USER_001" + String getMessage(); // "유저를 찾을 수 없습니다." + int getHttpStatus(); // 404 +} diff --git a/src/main/java/com/michelet/common/exception/GlobalExceptionHandler.java b/src/main/java/com/michelet/common/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..ce7decc --- /dev/null +++ b/src/main/java/com/michelet/common/exception/GlobalExceptionHandler.java @@ -0,0 +1,68 @@ +package com.michelet.common.exception; + +import com.michelet.common.response.ApiResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingRequestHeaderException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; + +/** + * 전역 예외 처리기. + */ +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + // 비즈니스 예외 (404, 403, 409 등) + @ExceptionHandler(BusinessException.class) + public ResponseEntity> handleBusinessException(BusinessException e) { + log.warn("[BusinessException] code={}, message={}", e.getErrorCode(), e.getMessage()); + return ResponseEntity + .status(e.getHttpStatus()) + .body(ApiResponse.fail(e.getErrorCode(), e.getMessage())); + } + + // @Valid 유효성 검증 실패 (요청 바디) + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleValidation(MethodArgumentNotValidException e) { + String message = e.getBindingResult().getFieldErrors().stream() + .map(fe -> fe.getField() + ": " + fe.getDefaultMessage()) + .findFirst() + .orElse("유효성 검증 실패"); + log.warn("[Validation] {}", message); + return ResponseEntity.badRequest() + .body(ApiResponse.fail("VALIDATION_001", message)); + } + + // Enum / UUID 등 타입 변환 실패 (@RequestParam, @PathVariable) + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ResponseEntity> handleTypeMismatch(MethodArgumentTypeMismatchException e) { + String message = e.getName() + " 파라미터 형식이 올바르지 않습니다."; + log.warn("[TypeMismatch] param={}, requiredType={}", + e.getName(), + e.getRequiredType() != null ? e.getRequiredType().getSimpleName() : "unknown"); + return ResponseEntity.badRequest() + .body(ApiResponse.fail("VALIDATION_002", message)); + } + + // 헤더 누락, 요청 바디 파싱 실패 (JSON 구조 오류 등) + @ExceptionHandler({MissingRequestHeaderException.class, HttpMessageNotReadableException.class}) + public ResponseEntity> handleBadRequest(Exception e) { + log.warn("[BadRequest] type={}", e.getClass().getSimpleName()); + return ResponseEntity.badRequest() + .body(ApiResponse.fail("VALIDATION_003", "요청 형식이 올바르지 않습니다.")); + } + + // 그 외 예상치 못한 서버 에러 + @ExceptionHandler(Exception.class) + public ResponseEntity> handleException(Exception e) { + log.error("[Unexpected Error]", e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(ApiResponse.fail("INTERNAL_001", "서버 오류가 발생했습니다.")); + } +} diff --git a/src/main/java/com/michelet/common/response/ApiResponse.java b/src/main/java/com/michelet/common/response/ApiResponse.java new file mode 100644 index 0000000..3fa1676 --- /dev/null +++ b/src/main/java/com/michelet/common/response/ApiResponse.java @@ -0,0 +1,51 @@ +package com.michelet.common.response; + +import com.fasterxml.jackson.annotation.JsonInclude; +import org.slf4j.MDC; + +import java.time.LocalDateTime; + +/** + * 모든 REST API 응답의 통일된 포맷. + * 성공/실패 구분, 분산 추적을 위한 traceId 를 포함한다. + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record ApiResponse( + boolean success, + T data, + String code, + String message, + LocalDateTime timestamp, + String traceId +) { + + public static ApiResponse ok(T data) { + return new ApiResponse<>(true, data, null, null, LocalDateTime.now(), currentTraceId()); + } + + public static ApiResponse ok() { + return new ApiResponse<>(true, null, null, null, LocalDateTime.now(), currentTraceId()); + } + + public static ApiResponse ok(SuccessCode code, T data) { + SuccessCode successCode = java.util.Objects.requireNonNull(code, "successCode must not be null"); + return new ApiResponse<>(true, data, successCode.getCode(), successCode.getMessage(), + LocalDateTime.now(), currentTraceId()); + } + + public static ApiResponse fail(String code, String message) { + String safeCode = java.util.Objects.requireNonNull(code, "code must not be null"); + String safeMessage = java.util.Objects.requireNonNull(message, "message must not be null"); + return new ApiResponse<>(false, null, safeCode, safeMessage, LocalDateTime.now(), currentTraceId()); + } + + /** + * Micrometer Tracing 이 MDC 에 넣어주는 traceId 를 꺼낸다. + * 로그와 응답의 traceId 를 일치시키는 것이 목적. + */ + private static String currentTraceId() { + String traceId = MDC.get("traceId"); + return traceId != null ? traceId : MDC.get("X-B3-TraceId"); + } +} diff --git a/src/main/java/com/michelet/common/response/SuccessCode.java b/src/main/java/com/michelet/common/response/SuccessCode.java new file mode 100644 index 0000000..681d16b --- /dev/null +++ b/src/main/java/com/michelet/common/response/SuccessCode.java @@ -0,0 +1,28 @@ +package com.michelet.common.response; + +/** + * 성공 응답에 부가적인 의미 코드를 담고 싶을 때 사용하는 인터페이스. + * 각 도메인 서비스에서 enum 으로 구현한다. + * + *
+ * public enum OrderSuccessCode implements SuccessCode {
+ *     ORDER_CREATED("ORDER_SUCCESS_001", "주문이 생성되었습니다."),
+ *     ORDER_CANCELED("ORDER_SUCCESS_002", "주문이 취소되었습니다.");
+ *
+ *     private final String code;
+ *     private final String message;
+ *
+ *     OrderSuccessCode(String code, String message) {
+ *         this.code = code;
+ *         this.message = message;
+ *     }
+ *
+ *     @Override public String getCode()    { return code; }
+ *     @Override public String getMessage() { return message; }
+ * }
+ * 
+ */ +public interface SuccessCode { + String getCode(); + String getMessage(); +} diff --git a/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 0000000..b992e41 --- /dev/null +++ b/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +com.michelet.common.config.CommonAutoConfiguration