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
์ด๋
ธํ
์ด์
์ ์ด์ฉํ๋ค.
package com.example;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice("example")
public class CommonExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public String handleRuntimeException() {
return "์์ธ ์ฒ๋ฆฌ ํ์ด์ง";
}
}
์์ ์์๋ ํน์ ํจํค์ง์ธ example ๋ฐ ํ์ ํจํค์ง์ ํด๋น ์์ธ ์ฒ๋ฆฌ ์ฝ๋๋ฅผ ์ ์ฉํ ๊ฒ๊ณผ ๊ฐ๋ค.
ํจํค์ง ์ด์ธ์๋ @ControllerAdvice
์ด๋
ธํ
์ด์
์ ๋ค์๊ณผ ๊ฐ์ ๋์์ ์ง์ ํ ์ ์๋ค.
ํน์ ํจํค์ง ๋ฐ ํ์ ํจํค์ง ๋ด์ ์ปจํธ๋กค๋ฌ
@ControllerAdvice(String[])
ํน์ ์ด๋ ธํ ์ด์ ์ด ์ ์ฉ๋ ์ปจํธ๋กค๋ฌ
@ControllerAdvice(Class<? extends Annotation>[])
ํน์ ํ์ ๋๋ ํ์ ํ์ ์ ์ปจํธ๋กค๋ฌ
@ControllerAdvice(Class<?>[])
์ ์ฉ ์ฐ์ ์์
์ปจํธ๋กค๋ฌ ๋ด๋ถ์ @ExceptionHandler
๋ฉ์๋ ์ค ํด๋น Exception์ ์ฒ๋ฆฌํ ์ ์๋ ๋ฉ์๋๊ฐ ์๋์ง ๋จผ์ ํ์ํ๋ค.
์๋ค๋ฉด @ControllerAdvice
๋ด์์ ํ์ํ๋ค.
์ฆ, @ExceptionHandler
โ @ControllerAdvice
์์์ด๋ค.
Last updated