project κ° μ»€μ§μλ‘ REST Controller μ κ°μλ λμ΄λ μ μλ€. κ·Έλ¬λ μ΄μ μ μμ±ν exception handler λ StudentRestController λΌλ νΉμ Controller μμλ§ μ ν¨νλ€. λ°λΌμ λͺ¨λ Controller μμ μ¬μ©ν μ μλ centralized λκ³ global ν exception handler κ° νμνλ€.
Spring @ControllerAdvice
@ControllerAdvice annotation μ ν΅ν© μμΈ μ²λ¦¬ μΌν°λΌκ³ ν μ μλ€. λνμ μΌλ‘ μλ λ κ°μ νΉμ±μ κ°μ§λ€.
- request λ₯Ό pre-process νμ¬ controller μκ² μ λ¬
- exception handling μ μνμ¬ response λ₯Ό post-process
Global Exception Handling

μμ κ°μ΄ Controller Advice λ₯Ό ν΅νλλ‘ μ€κ³νλ©΄ λ κ² κ°λ€. Development Process λ λ€μκ³Ό κ°λ€.
- Create new
@ControllerAdvice- Refactoring REST service: remove exception handlind code
- Add exception handling code to
@ControllerAdvice
Step 1: Create new @ControllerAdvice
@ControllerAdvice
public class StudentExceptionHandler {
...
}λ¨Όμ StudentExceptionHandler class λ₯Ό μλ‘ μμ±νκ³ @ControllerAdvice annotation μΌλ‘ μ§μ νμ.
Step 2: Refactoring REST service - remove exception handlind code
κΈ°μ‘΄μ νΉμ Controller μμ μλ exception handling code λΆλΆμ λͺ¨λ μμ νλ€.
Step 3: Add exception handling code to @ControllerAdvice
Step 2 μμ μμ ν code snippet μ κ·Έλλ‘ StudentExceptionHandler μ paste νμ¬ μ¬μ©νλ€.
μ΄λ κ² λλ©΄ exception handler κ° νΉμ Controller μ μ’ μλλ κ²μ΄ μλλΌ Controller Advice κ° λͺ¨λ exception handling μ μ²λ¦¬νκ² λλ€.
@ControllerAdvice λ AOP(Aspect-Oriented Programming) μ μ리λ₯Ό κΈ°λ°μΌλ‘ λμνλ©°, Controller μμ λ°μνλ exception μ global νκ² μ²λ¦¬νκΈ° μν κΈ°λ₯μ΄λ€. AOP μ SoC(Seperation of Concerns) κ°λ
μ νμ©νμ¬ λͺ¨λ Controller μ 곡ν΅λ logic μ μ μ©νμ¬ μ²λ¦¬ν μ μλ€.
test ν΄λ³΄λ©΄, κΈ°μ‘΄ Controller μ exception handling λΆλΆμ΄ μμ΄μ‘μΌλ μλ‘ λ§λ€μ΄μ§ Controller Advice κ° exception handling μ μ±κ³΅μ μΌλ‘ μνν κ²μ λ³Ό μ μλ€.