본문 바로가기

Backend

[Spring Boot]GlobalExceptionHandler (Feat. @ControllerAdvice)

반응형

코드를 작성하다 보면 중복으로 작성하는 코드가 생기기 마련이다.

그 중에서도 예외 처리 코드의 경우가 대표적이다.

 

중복되는 코드를 방지하기 위해 ExceptionHandler를 별도로 관리하는 전용 패키지를 생성해 준다.

Resource가 없을 때 발생 시키는 ExceptionHandler와 전역으로 관리할 GlobalExceptionHandler 클래스를 생성했다.

ResourceNotFoundException 

ResponseStatus value로 NOT_FOUND 상태를 받는다.

RuntimeException클래스로부터 'message' 변수를 참조해서 메시지를 구성했다.

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String resourceName, String fieldName, String fieldValue) {
        super(String.format("%s not found with the given input data %s : '%s'", resourceName, fieldName, fieldValue));
    }
}

 

GlobalExceptionHandler

ErrorResponseDto를 별도로 구성해서 에러 발생 시 지정한 포맷에 맞춰 리턴할 수 있도록 했다. ResourceNotFoundExceptionHandler로 처리한 NOT_FOUND 에러와는 별도로 서버에러 발생 시 에러 메시지를 리턴할 수 있도록 ExceptionHandler를 구성했다.

@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponseDto> handleGlobalException(Exception exception,
                                                                  WebRequest webRequest) {
        ErrorResponseDto errorResponseDTO = new ErrorResponseDto(
                webRequest.getDescription(false),
                HttpStatus.INTERNAL_SERVER_ERROR,
                exception.getMessage(),
                LocalDateTime.now()
        );
        return new ResponseEntity<>(errorResponseDTO, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponseDto> handleResourceNotFoundException(ResourceNotFoundException exception,
                                                                            WebRequest webRequest) {
        ErrorResponseDto errorResponseDTO = new ErrorResponseDto(
                webRequest.getDescription(false),
                HttpStatus.NOT_FOUND,
                exception.getMessage(),
                LocalDateTime.now()
        );
        return new ResponseEntity<>(errorResponseDTO, HttpStatus.NOT_FOUND);
    }
}

 

 

@ControllerAdvice는 ExceptionHandler를 전역에서 처리할 수 있게 도와주는 어노테이션으로, Spring Boot에서 제공해 주는 기능이다. @ControllerAdvice 만 붙여주면 여러 Controller에서 공통적으로 발생하는 공통 에러를 처리 할 수 있다.

 

 

반응형