Closed isayaksh closed 11 months ago
ํ์ฌ ์๋ฒ์์ Exception์ด ๋ฐ์ํ ๊ฒฝ์ฐ @RestControllerAdvice์์ ์ฒ๋ฆฌํ๊ณ ์๋ค. ํด๋ผ์ด์ธํธ์์ ์์ฒญ์ ๋ณด๋ด๊ณ ๋ฌธ์ ๊ฐ ๋ฐ์ํ ๋ ๋ง๋ค ์๋ฒ์ ๋ก๊ทธ๋ฅผ ํ์ธํ์ฌ ํน์ Exception์ ์ฐพ์๋ด๊ณ ํด๋น Exception์ ๋ํ Handler๋ฅผ ์ถ๊ฐํ๋ ๋ฐฉ์์ผ๋ก ์งํํ๊ณ ์์๋ค.
@RestControllerAdvice
๋ง์ฝ handler์ ๋ฑ๋กํ์ง ์์ Exception์ด ๋ฐ์ํ๋ค๋ฉด trace์์ ์ด์ํ๊ฒฝ์์์ ๊ตฌํ์ด ๋ ธ์ถ๋๋ค๋ ๋ฌธ์ ์ ์ด ์๋ค.
All exception classes are subtypes of the java.lang.Exception class. The Exception class is a subclass of the Throwable class. Other than the Exception class there is another subclass called Error which is derived from the Throwable class.
์ ๋ด์ฉ์ ์ดํด๋ณด๋ฉด Exception.class๋ ๋ชจ๋ Exception์ Base class๋ผ๋ ๊ฒ์ ์ ์ ์๋ค.
Exception.class
๋งค๋ฒ ์์ธ๊ฐ ๋ฐ์ํ ๋๋ง๋ค ํด๋น Exception์ ๋ํ handler๋ฅผ ์ถ๊ฐํ๋ ๊ฒ์ ์์ธ์ ๋ํ ์์ธํ ์ ๋ณด๋ฅผ ์ ๋ฌํ๊ธฐ ์ํด์ ํ์ํ๋ค. ํ์ง๋ง, ์๋ฒ์์ ์ฒ๋ฆฌํ ์ ์๋ Exception์ ์์ด์ผ ํ๋ฏ๋ก ๋ฐ์ํ Exception์ด Handler์ ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ default๋ก ํด๋น Exception์ ๋ค๋ค์ค Handler๋ฅผ ๋ฑ๋กํ์๋ค.
@ExceptionHandler(Exception.class) public ResponseEntity exception(Exception e) { log.error(e.getMessage()); return new ResponseEntity(new ResponseDto<>(-1, e.getMessage(), "์๋ฒ์์ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. Issue๋ฅผ ๋จ๊ฒจ์ฃผ์ธ์!"), HttpStatus.BAD_REQUEST); }
์กฐ๊ธ๋ง ์๊ฐํด๋ณด๋ฉด Exception.class๊ฐ ๋ชจ๋ Exception์ base class์ธ ๊ฒ์ ์๊ณ Handler์ฒ๋ฆฌ๋ฅผ ํ ์ ์์๋๋ฐ ๋๋ฌด ์๋์ ์ผ๋ก ์๊ฐํ๋ ๊ฒ ๊ฐ๋ค.
๐ฅ Problem
ํ์ฌ ์๋ฒ์์ Exception์ด ๋ฐ์ํ ๊ฒฝ์ฐ
@RestControllerAdvice
์์ ์ฒ๋ฆฌํ๊ณ ์๋ค. ํด๋ผ์ด์ธํธ์์ ์์ฒญ์ ๋ณด๋ด๊ณ ๋ฌธ์ ๊ฐ ๋ฐ์ํ ๋ ๋ง๋ค ์๋ฒ์ ๋ก๊ทธ๋ฅผ ํ์ธํ์ฌ ํน์ Exception์ ์ฐพ์๋ด๊ณ ํด๋น Exception์ ๋ํ Handler๋ฅผ ์ถ๊ฐํ๋ ๋ฐฉ์์ผ๋ก ์งํํ๊ณ ์์๋ค.๋ง์ฝ handler์ ๋ฑ๋กํ์ง ์์ Exception์ด ๋ฐ์ํ๋ค๋ฉด trace์์ ์ด์ํ๊ฒฝ์์์ ๊ตฌํ์ด ๋ ธ์ถ๋๋ค๋ ๋ฌธ์ ์ ์ด ์๋ค.
๐ก Solution
์ ๋ด์ฉ์ ์ดํด๋ณด๋ฉด
Exception.class
๋ ๋ชจ๋ Exception์ Base class๋ผ๋ ๊ฒ์ ์ ์ ์๋ค.๋งค๋ฒ ์์ธ๊ฐ ๋ฐ์ํ ๋๋ง๋ค ํด๋น Exception์ ๋ํ handler๋ฅผ ์ถ๊ฐํ๋ ๊ฒ์ ์์ธ์ ๋ํ ์์ธํ ์ ๋ณด๋ฅผ ์ ๋ฌํ๊ธฐ ์ํด์ ํ์ํ๋ค. ํ์ง๋ง, ์๋ฒ์์ ์ฒ๋ฆฌํ ์ ์๋ Exception์ ์์ด์ผ ํ๋ฏ๋ก ๋ฐ์ํ Exception์ด Handler์ ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ default๋ก ํด๋น Exception์ ๋ค๋ค์ค Handler๋ฅผ ๋ฑ๋กํ์๋ค.
์กฐ๊ธ๋ง ์๊ฐํด๋ณด๋ฉด
Exception.class
๊ฐ ๋ชจ๋ Exception์ base class์ธ ๊ฒ์ ์๊ณ Handler์ฒ๋ฆฌ๋ฅผ ํ ์ ์์๋๋ฐ ๋๋ฌด ์๋์ ์ผ๋ก ์๊ฐํ๋ ๊ฒ ๊ฐ๋ค.