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 λŠ” λ‹€μŒκ³Ό κ°™λ‹€.

  1. Create new @ControllerAdvice
  2. Refactoring REST service: remove exception handlind code
  3. 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 을 μ„±κ³΅μ μœΌλ‘œ μˆ˜ν–‰ν•œ 것을 λ³Ό 수 μžˆλ‹€.