@ExceptionHandler

Yuno·2024년 8월 18일
0

Spring Framework 에서 발생한 특정 예외를 처리하기 위해 사용되는 어노테이션.
특정 예외가 발생했을때, 그 예외를 처리하는 메서드를 지정할 수 있음
주로 Spring MVC에서 컨트롤러 계층에서 발생하는 예외를 처리할 때 많이 사용됨


👉 기본 사용

@RestController
@RequestMapping("/api")
public class MyController {
	
    @GetMapping("/example")
    public String exampleMethod() {
    	if (ture) { // 예제이므로 항상 예외 발생
        	throw new RuntimeException("Runtime Exception 발생!");
    }
    return "Hello, World!";

	@ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
    	return new ResponseEntity<>("RuntimeException 처리: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
  • @ExceptionHandler(RuntimeException.class) : RuntimeException 이 발생했을 때 호출될 메서드를 정의
  • handleRuntimeException(RuntimeException ex) : 예외가 발생했을 때 처리하는 로직을 담고 있는 메서드. 여기서는 예외 메세지를 클라이언트에 반환하고, HTTP 상태 코드를 500 INTERNAL SERVER ERROR 로 설정함

👉 여러 예외 처리

하나의 컨트롤러에서 여러 종류의 예외를 처리할 수 있음. 예를 들어, IllegalArgumentExceptionNullPointerException 을 처리하는 메서드를 각각 정의할 수 있음.

@RestController
@RequestMapping("/api")
public class MyController {
	
    @GetMapping("/example")
    public String exampleMethod() {
    	if (true) {
        	throw new IllegalArgumentException("잘못된 인자!");
        }
        return "Hello, World!";
    }
    
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handlerIllegalArgumentException(IllegalArgumentException ex) {
    	return new ResponseEntity<>("IllegalArgumentException 처리: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
    }
    
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<String> handlerNullPointerException(NullPointerException ex) {
    	return new ResponseEntity<>("NullpointerException 처리: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
  • @ExceptionHandler(IllegalArgumentException.class) : IllegalArgumentException 을 처리하는 메서드
  • @ExceptionHandler(NullPointerException.class) : NullpointerException 을 처리하는 메서드

👉 글로벌 예외 처리

특정 컨트롤러가 아닌, 어플리케이션 전역에서 발생하는 예외를 처리하려면, @ControllerAdvice 와 함께 @ExceptionHandler 를 사용

@ControllerAdvice
public class GlobalExceptionHandler {
	
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handlerAllException(Exception ex) {
    	return new ResponseEntity<>("예외 처리: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handlerIllegalArgumentException(IllegarArgumentException ex) {
    	return new ResponseEntity<>("잘못된 인자 처리: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
  • @ControllerAdvice : 이 클래스가 전역 예외 처리를 위한 컨트롤러 어드바이스임을 나타냄
  • @ExceptionHandler(Exception.class) : 모든 예외를 처리하는 메서드를 정의
  • @ExceptionHandler(IllegalArgumentException.class) : 특정 예외(여기서는 IllegalArgumentException)를 처리하는 메서드를 정의

👉 응답 형식

예외 처리 메서드는 다양한 응답 형식을 사용할 수 있음. 예를 들어, JSON 형식으로 예외 메세지를 반환할 수도 있음.

@ExceptionHandler(MyCustomException.class)
public ResponseEntity<Map<String, String>> handlerMyCustomException(MyCustomException ex) {
	Map<String, String> errorResponse = new HashMap<>();
    errorResponse.put("error", ex.getMessage());
    errorResponse.put("status", "CUSTOM_ERROR");
    return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
  • Map<String, String> 을 반환하여 JSON 형식으로 에러 메세지를 전달.
  • HttpStatus.BAD_REQUEST : HTTP 상태 코드를 400 BAD REQUEST 로 설정함
profile
Hello World

0개의 댓글