
Spring Framework에서는 다양한 방법으로 예외처리를 할 수 있는데 그 중 하나는
@ExceptionHandler 어노테이션을 사용하는 것이다.
@ExceptionHandler 어노테이션을 사용하면 특정 예외가 발생했을 때 해당 예외를 처리하는 메서드를 정의할 수 있습니다.
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleIllegalArgumentException(IllegalArgumentException ex) {
return new ErrorResponse("400", ex.getMessage());
}
}
class ErrorResponse {
private String code;
private String message;
public ErrorResponse(String code, String message) {
this.code = code;
this.message = message;
}
// getters and setters
}
@RestControllerAdvice : 모든 @RestController 에 적용되는 전역 예외 처리기를 정의합니다.@ExceptionHandler : 특정 예외를 처리하는 메서드를 지정합니다.@ResponseStatus : HTTP 상태 코드를 지정합니다. 위 예제에서는 400 (BAD REQUEST) 상태 코드를 반환합니다.특정 컨트롤러에만 예외 처리를 적용하고 싶다면, 해당 컨트롤러 클래스 내에 @ExceptionHandler 메서드를 정의할 수 있습니다.
@RestController
public class MyController {
@GetMapping("/example")
public String example() {
throw new IllegalArgumentException("잘못된 요청입니다.");
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleIllegalArgumentException(IllegalArgumentException ex) {
return new ErrorResponse("400", ex.getMessage());
}
}
@ExceptionHandler : 해당 컨트롤러 내에서 발생하는 예외를 처리합니다.@ControllerAdvice 또는 @RestControllerAdvice : 애플리케이션 전체에서 발생하는 예외를 처리합니다.@ResponseStatus : 컨트롤러 메서드에 직접 적용하여 특정 예외 발생 시 상태 코드를 반환합니다.HandlerExceptionResolver 인터페이스를 구현하여 보다 세밀한 예외 처리를 할 수 있습니다.