[Spring] Exception Handler 사용하기

Minhyeok·2024년 6월 11일
post-thumbnail

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) 상태 코드를 반환합니다.

Local Exception Handling

특정 컨트롤러에만 예외 처리를 적용하고 싶다면, 해당 컨트롤러 클래스 내에 @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 인터페이스를 구현하여 보다 세밀한 예외 처리를 할 수 있습니다.

예외 처리의 Best Practice

  • 예외 메세지에 민감한 정보를 포함하지 않는다.
  • 사용자에게 의미 있는 오류 메세지를 제공한다.
  • 로깅을 통해 예외 발생 지점과 원인을 추적할 수 있도록 한다.
profile
민혁스

0개의 댓글