Skip to content

Latest commit

ย 

History

History
55 lines (48 loc) ยท 2.13 KB

Exception Handler.md

File metadata and controls

55 lines (48 loc) ยท 2.13 KB

1.Exception Handler

์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋‚ด์—์„œ ๋ฐœ์ƒํ•˜๋Š” ์˜ˆ์™ธ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฉ”์ปค๋‹ˆ์ฆ˜์„ ์ œ๊ณตํ•˜๋Š” ๊ธฐ๋Šฅ์ž…๋‹ˆ๋‹ค.
์ฃผ๋กœ @Controller ๋˜๋Š” @RestController ํด๋ž˜์Šค ๋‚ด๋ถ€์—์„œ ์ •์˜๋˜๋ฉฐ, 
ํŠน์ • ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ ํ•ด๋‹น ์˜ˆ์™ธ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ์ง€์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@ExceptionHandler,@ControllerAdvice ์• ๋…ธํ…Œ์ด์…˜์„ ์‚ฌ์šฉํ•œ๋‹ค.

2.Exception Handler ์‚ฌ์šฉ์˜ˆ์‹œ

2-1. @ExceptionHandler

RuntimeException์ด ๋ฐœ์ƒํ•˜๋ฉด, handleRuntimeException ๋ฉ”์„œ๋“œ๊ฐ€ ํ•ด๋‹น 
์˜ˆ์™ธ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ํ•œ๋‹ค.
@RestController
@RequestMapping("/api")
public class MyController {

    @GetMapping("/example")
    public String example() {
        if (true) {
            throw new RuntimeException("This is a runtime exception");
        }
        return "example";
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return new ResponseEntity<>("Exception handled: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

2-2.@ControllerAdvice(๊ธ€๋กœ๋ฒŒ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ)

@ControllerAdvice๋Š” ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ „์—ญ์—์„œ ๋ฐœ์ƒํ•˜๋Š” ์˜ˆ์™ธ๋ฅผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๊ฒŒ 
ํ•ด์ค๋‹ˆ๋‹ค.
GlobalExceptionHandler ํด๋ž˜์Šค๊ฐ€ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ „์—ญ์—์„œ ๋ฐœ์ƒํ•˜๋Š” 
RuntimeException ๋ฐ Exception์„ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค.
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return new ResponseEntity<>("Global Exception handled: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        return new ResponseEntity<>("Global Exception handled: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
    }
}