SeouliteLab

[Java/자바] Spring @ExceptionHandler: 예외 처리하기 본문

프로그래밍

[Java/자바] Spring @ExceptionHandler: 예외 처리하기

Seoulite Lab 2024. 3. 12. 11:03

Spring 프레임워크에서 @ExceptionHandler 어노테이션은 컨트롤러 내에서 발생하는 예외를 처리할 때 사용됩니다. 이 글에서는 @ExceptionHandler 어노테이션의 사용법과 예제 코드를 통해 자세히 알아보겠습니다.

1. 기본적인 @ExceptionHandler 사용법

가장 간단한 형태의 @ExceptionHandler 어노테이션은 다음과 같이 컨트롤러 클래스 내에서 사용됩니다.

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public String handleException(Exception ex) {
        return "An error occurred: " + ex.getMessage();
    }
}

위의 예제에서는 모든 예외를 처리하고, HTTP 상태 코드를 500으로 설정하여 서버 오류를 응답합니다.

2. 특정 예외 처리하기

특정한 예외에 대해서만 처리하고 싶을 경우, @ExceptionHandler 어노테이션을 해당 예외 타입에 적용합니다.

예제 1: 특정 예외 처리하기

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public String handleResourceNotFoundException(ResourceNotFoundException ex) {
        return "Resource not found: " + ex.getMessage();
    }
}

위의 예제에서는 ResourceNotFoundException 예외가 발생했을 때만 처리하고, HTTP 상태 코드를 404로 설정하여 리소스를 찾을 수 없음을 응답합니다.

3. 예제 코드

다음은 @ExceptionHandler 어노테이션을 사용한 예제 코드입니다.

예제 1: 기본적인 @ExceptionHandler 사용법

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public String handleException(Exception ex) {
        return "An error occurred: " + ex.getMessage();
    }
}

예제 2: 특정 예외 처리하기

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public String handleResourceNotFoundException(ResourceNotFoundException ex) {
        return "Resource not found: " + ex.getMessage();
    }
}

4. 결론

이상으로 Spring의 @ExceptionHandler 어노테이션에 대한 자세한 설명과 예제 코드를 살펴보았습니다. @ExceptionHandler 어노테이션을 사용하여 컨트롤러 내에서 발생하는 예외를 쉽게 처리할 수 있습니다.