Exception Handling

컨트둀러 λ‚΄μ—μ„œμ˜ μ˜ˆμ™Έ 처리

@ExceptionHandler μ–΄λ…Έν…Œμ΄μ…˜μ„ μ΄μš©ν•œλ‹€. ν•΄λ‹Ή μ–΄λ…Έν…Œμ΄μ…˜μ˜ νŒŒλΌλ―Έν„°λ‘œ μ „λ‹¬λœ μ˜ˆμ™Έκ°€ λ°œμƒν•˜λ©΄ ν•΄λ‹Ή handlerλ₯Ό μ‹€ν–‰ν•œλ‹€.


import org.springframework.beans.TypeMismatchException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class HelloController {

		... μ€‘λž΅

    @ExceptionHandler(TypeMismatchException.class)
    public String handleTypeMismatchException() {
        return "μ˜ˆμ™Έ 처리 νŽ˜μ΄μ§€";
    }

}

곡톡 μ˜ˆμ™Έ 처리

컨트둀러 λ‚΄λΆ€μ—μ„œκ°€ μ•„λ‹Œ νŠΉμ • νŒ¨ν‚€μ§€ 등을 λŒ€μƒμœΌλ‘œ 곡톡적인 μ˜ˆμ™Έ 처리λ₯Ό μˆ˜ν–‰ν•  μˆ˜λ„ μžˆλ‹€.

이λ₯Ό μœ„ν•΄ @ControllerAdvice μ–΄λ…Έν…Œμ΄μ…˜μ„ μ΄μš©ν•œλ‹€.

μœ„μ˜ μ˜ˆμ‹œλŠ” νŠΉμ • νŒ¨ν‚€μ§€μΈ example 및 ν•˜μœ„ νŒ¨ν‚€μ§€μ— ν•΄λ‹Ή μ˜ˆμ™Έ 처리 μ½”λ“œλ₯Ό μ μš©ν•œ 것과 κ°™λ‹€.

νŒ¨ν‚€μ§€ 이외에도 @ControllerAdvice μ–΄λ…Έν…Œμ΄μ…˜μ€ λ‹€μŒκ³Ό 같은 λŒ€μƒμ— μ§€μ •ν•  수 μžˆλ‹€.

  1. νŠΉμ • νŒ¨ν‚€μ§€ 및 ν•˜μœ„ νŒ¨ν‚€μ§€ λ‚΄μ˜ 컨트둀러

  2. νŠΉμ • μ–΄λ…Έν…Œμ΄μ…˜μ΄ 적용된 컨트둀러

  3. νŠΉμ • νƒ€μž… λ˜λŠ” ν•˜μœ„ νƒ€μž…μ˜ 컨트둀러

적용 μš°μ„  μˆœμœ„

컨트둀러 내뢀에 @ExceptionHandler λ©”μ„œλ“œ 쀑 ν•΄λ‹Ή Exception을 μ²˜λ¦¬ν•  수 μžˆλŠ” λ©”μ„œλ“œκ°€ μžˆλŠ”μ§€ λ¨Όμ € νƒμƒ‰ν•œλ‹€.

μ—†λ‹€λ©΄ @ControllerAdvice λ‚΄μ—μ„œ νƒμƒ‰ν•œλ‹€.

즉, @ExceptionHandler β†’ @ControllerAdvice μˆœμ„œμ΄λ‹€.

Last updated