SWM-99-degree / jariBean

SWM 14th JariBean Project
0 stars 1 forks source link

[REFACTOR] handling all of exception #219

Closed isayaksh closed 11 months ago

isayaksh commented 11 months ago

๐Ÿ”ฅ Problem

ํ˜„์žฌ ์„œ๋ฒ„์—์„œ Exception์ด ๋ฐœ์ƒํ•  ๊ฒฝ์šฐ @RestControllerAdvice์—์„œ ์ฒ˜๋ฆฌํ•˜๊ณ  ์žˆ๋‹ค. ํด๋ผ์ด์–ธํŠธ์—์„œ ์š”์ฒญ์„ ๋ณด๋‚ด๊ณ  ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•  ๋•Œ ๋งˆ๋‹ค ์„œ๋ฒ„์˜ ๋กœ๊ทธ๋ฅผ ํ™•์ธํ•˜์—ฌ ํŠน์ • Exception์„ ์ฐพ์•„๋‚ด๊ณ  ํ•ด๋‹น Exception์— ๋Œ€ํ•œ Handler๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰ํ•˜๊ณ  ์žˆ์—ˆ๋‹ค.

๋งŒ์•ฝ handler์— ๋“ฑ๋กํ•˜์ง€ ์•Š์€ Exception์ด ๋ฐœ์ƒํ•œ๋‹ค๋ฉด trace์—์„œ ์šด์˜ํ™˜๊ฒฝ์—์„œ์˜ ๊ตฌํ˜„์ด ๋…ธ์ถœ๋œ๋‹ค๋Š” ๋ฌธ์ œ์ ์ด ์žˆ๋‹ค.

๐Ÿ’ก Solution

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์— ๋Œ€ํ•œ 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์ฒ˜๋ฆฌ๋ฅผ ํ•  ์ˆ˜ ์žˆ์—ˆ๋Š”๋ฐ ๋„ˆ๋ฌด ์ˆ˜๋™์ ์œผ๋กœ ์ƒ๊ฐํ–ˆ๋˜ ๊ฒƒ ๊ฐ™๋‹ค.