Spring ExceptionResolver
Springboot๊ฐ ์ ๊ณตํ๋ ExceptionResolver๊ฐ ์กด์ฌํ๋๋ฐ HandlerExceptionResolverComosite์ ๋ค์ ์์๋ก ๋ฑ๋ก๋๋ค. (์ฐ์ ์์)
ExceptionHandlerExceptionResolver
ResponseStatusExceptionResolver โ ๊ฐ๋ฐ์๊ฐ ์๋ต ์ฝ๋ ๋ณ๊ฒฝ
DefaultHandlerExceptionResolover โ ์คํ๋ง ๋ด๋ถ์์ ์์ฒด์ ์ผ๋ก ์ฒ๋ฆฌ
์์ธ๊ฐ ExceptionHandlerExceptionResolver์์ ์ฒ๋ฆฌ๋๋ฉด ์ดํ์ resolver๋ ์งํ๋์ง ์๊ณ null์ด ๋ฐํ๋ ๊ฒฝ์ฐ ๋ค์ resolver๋ฅผ ํธ์ถํ๋ค.
ResponseStatusExceptionResolver
์์ธ์ ๋ฐ๋ผ์ HTTP ์ํ ์ฝ๋๋ฅผ ์ง์ ํ๋ resolver์ด๋ค.
@ResponseStatus ์ด๋ ธํ ์ด์ ์ด ์๋ ์์ธ
ResponseStatusException ์์ธ
@ResponseStatus
@ResponseStatus(code = HttpStatus.XXX, reasone = "error message")
public class CustomExcpeiton extends RuntimeException {
...
}์ ์ํ ํด๋์ค๋ฅผ ๋๊ฒจ์ฃผ๋ฉด, ์ํ ์ฝ๋์ ์๋ฌ ๋ฉ์์ง๋ฅผ ๋ด๋ถ์ ์ผ๋ก response.sendError()์ ๋ฃ์ด์ฃผ๊ณ ModelAndView()๋ฅผ return ํ๋ค.
ResponseStatusException
@ResponseStatus ์ด๋ ธํ ์ด์ ์ ๊ฐ๋ฐ์๊ฐ ๋ณ๊ฒฝํ ์ ์๋ ๊ณณ์๋ ์ ์ฉํ ์ ์๋ค. ์ด๋ ธํ ์ด์ ์ ์์ฑํด์ผ ํ๋๋ฐ, ์ฝ๋๋ฅผ ์์ ํ ์ ์๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ์์ธ ์ฝ๋ ๊ฐ์ ๊ณณ์ ์ ์ฉ์ด ๋ถ๊ฐ๋ฅํ๋ค.
์ด๋๋ ResponseStatusException ์์ธ๋ฅผ ์ฌ์ฉํ๋ค.
์์ ๋ ๊ฒฝ์ฐ ์ ๋ถ ResponseStatusExceptionResolver๊ฐ ์์ธ๋ฅผ ์ฒ๋ฆฌํด์ค๋ค.
์์ธ๋ฅผ ์ฒ๋ฆฌํ ๋ ๋ด๋ถ์
doResolveException()์ด ํธ์ถ๋จ.
DefaultHandlerExceptionResolover
์คํ๋ง ๋ด๋ถ์์ ๋ฐ์ํ๋ ์คํ๋ง ์์ธ๋ฅผ ํด๊ฒฐํ๋ resolver์ด๋ค.
๋ํ์ ์ผ๋ก ํ๋ผ๋ฏธํฐ ๋ฐ์ธ๋ฉ ์์ ์ ํ์ ์ด ๋ง์ง ์์ผ๋ฉด ๋ด๋ถ์์ TypeMismatchException์ด ๋ฐ์ํ๋๋ฐ, ์์ธ๋ฅผ ์ฒ๋ฆฌํ์ง ์์ผ๋ฉด ์๋ธ๋ฆฟ ์ปจํ ์ด๋๊น์ง ์ ๋ฌ๋๊ณ 500 ์๋ฌ๋ฅผ ๋ฐํํ๋ค.
ํ๋ผ๋ฏธํฐ ๋ฐ์ธ๋ฉ์ ๋๋ถ๋ถ ํด๋ผ์ด์ธํธ๊ฐ HTTP ์์ฒญ ์ ๋ณด๋ฅผ ์๋ชป ํธ์ถํด์ ๋ฐ์ํ๋๋ฐ, ์ด๋ฐ ๊ฒฝ์ฐ HTTP ์ํ ์ฝ๋ 400์ ์ฌ์ฉํ๊ฒ ๋์ด์๋ค.
์ด resolver๋ ์ด๊ฒ์ 500์ด ์๋๋ผ 400์ผ๋ก ๋ฐํํ๋๋ก ๋ณ๊ฒฝํ๋ค.
handleTypeMismatch()์ ๋ด๋ถ์์๋ send.Error(SC_BAD_REQUEST)๋ฅผ ํธ์ถํ๋ค.
์์ ๊ฐ์ HandlerExceptionResolver๋ค์ ์ง์ ์ฌ์ฉํ๊ธฐ ๋ณต์กํ๋ค. API ์ค๋ฅ์๋ response.sendError()๋ฅผ ํตํด ์ง์ ๋ฐ์ดํฐ๋ฅผ ๋ฃ์ด์ผ ํ๊ณ , ModelAndView๋ฅผ ๋ฆฌํดํ๋ ๊ฒ๋ ์ ํฉํ์ง ์๋ค.
์คํ๋ง์ ์ด๊ฒ์ ํด๊ฒฐํ๊ธฐ ์ํด @ExceptionHandler๋ผ๋ ์์ธ ์ฒ๋ฆฌ ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ค.
์ด๊ฒ์ ์ ์ดํ๋ ๊ฒ์ด ExceptionHandlerExceptionResolver์ด๋ค.
@ExceptionHandler
์์ธ์ ๋ํ ๋ณ๋์ ์ค์ ์ด ์์ผ๋ฉด BasicErrorController๋ก ์ ๋ฌ๋๋ค.
์ด๋ ๊ฒ BasicErrorController๋ฅผ ์ฌ์ฉํ๊ฑฐ๋ HandlerExceptioResolver๋ฅผ ๊ตฌํํ๋ ๋ฐฉ์์ ๋ชจ๋ API ์๋ฌ๋ฅผ ์ ์ดํ๊ธฐ ์ฝ์ง ์๋ค.
resolver๋ฅผ ๊ตฌํํ๋ฉด json ํํ๋ก ๋ณํํ๊ณ , HttpServletResponse์ ์ง์ ์๋ต ๋ฐ์ดํฐ๋ฅผ ๋ฃ์ด์ฃผ๊ณ , ModelAndView๋ฅผ ๋ฐํํ๋ค.
์ ๋ฐฉ์์ ๋ค๋ฅธ ๋๋ฉ์ธ ์ปจํธ๋กค๋ฌ์์ ๋ฐ์ํ๋ ๊ฐ์ Exception(RuntimeException ๊ฐ์)์ ๋ค๋ฅธ ํํ๋ก ๋ค๋ฃจ๊ธฐ ์ด๋ ต๋ค.
์คํ๋ง์ ์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด์ @ExceptionHandler๋ฅผ ์ฌ์ฉํด์ExceptionHandlerExceptionResolver๋ฅผ ๋์ํ๋ค.
์์ธ๊ฐ ๋ฐ์ํ๋ฉด ExceptionHandlerResolver๊ฐ ์ปจํธ๋กค๋ฌ์์ @ExceptionHandler๊ฐ ์กด์ฌํ๋์ง ํ์ํ๋ค.
์กด์ฌํ๋ค๋ฉด ์คํํ๊ณ ์ ์์ ์ธ ํ๋ฆ์ผ๋ก ๋ฐ๊ฟ์ returnํ๋ค. ์์ธ๊ฐ ๋ฐ์ํ์ง๋ง, ์ ์ ํ๋ฆ์ผ๋ก ๋ฐํํ๋ฉด ์ํ ์ฝ๋๋ฅผ 200์ผ๋ก ์ ๋ฌํ๋ค. (์์ธ๋ ์ฒ๋ฆฌํจ.)
์ ์ ํ๋ฆ์ผ๋ก ๋ฐ๋๋ฉด, ์๋ธ๋ฆฟ ์ปจํ ์ด๋์ ์์ธ๋ฅผ ์ ๋ฌํ๊ณ ์๋ธ๋ฆฟ ์ปจํ ์ด๋์์ ๋ค์ ์๋ฌ ์ฒ๋ฆฌ ์์ฒญ์ ๋ณด๋ด๊ณ ๊ทธ๋ฌ์ง ์๋๋ค.
๋ฐ๋ผ์ ์ํ ์ฝ๋๋ ๋ณ๊ฒฝํ๊ณ ์ถ์ผ๋ฉด @ResponseStatus()๋ฅผ ์ฌ์ฉํ๋ค.
Last updated