Spring

[Spring] Spring MVC - 예외처리

ryureeru 2022. 10. 24. 15:53

Spring MVC - 예외처리

 

 

1. @ExceptionHandler

  • 컨트롤러 기반의 예외 처리
  • HTTP Status code를 변경하는 방법
    • @ResponseStatus
    • ResponseEntity 활용
// @ResponseStatus(HttpStatus.FORBIDDEN) // FORBIDDEN은 403, OK는 200, ...
@ExceptionHandler(IllegalAccessException.class)
public ResponseEntity<ErrorResponse> handleIllegalAccessException(
        IllegalAccessException e) {
    log.error("IllegalAccessExcepetion is occurred.", e);

    // json으로 응답하기 위해 (직렬화에 수월)
    return ResponseEntity
            .status(HttpStatus.FORBIDDEN)
            .header("newHeader", "Some Value")
            .body(new ErrorResponse(ErrorCode.TOO_BIG_ID_ERROR,
                    "IllegalAccess is occurred."));
}

 

 

2. @RestControllerAdvice

  • 어플리케이션의 전 .역. 적 예외 처리
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(AccountException.class)
    public ErrorResponse handleAccountException(AccountException e) {
        log.error("{} is occured", e.getErrorCode());

        return new ErrorResponse(e.getErrorCode(), e.getErrorMessage());
    }

    // DB에 어떤 unique key가 있는데, 그 키가 중복돼서 저장하려 할 때
    @ExceptionHandler(DataIntegrityViolationException.class)
    public ErrorResponse handleDataIntegrityViolationException (DataIntegrityViolationException e) {
        log.error("DataIntegrityViolationException is occurred", e);

        return new ErrorResponse(INVALID_REQUEST, INVALID_REQUEST.getDescription());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ErrorResponse handleMethodArgumentNotValidException (MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException is occurred", e);

        return new ErrorResponse(INVALID_REQUEST, INVALID_REQUEST.getDescription());
    }

    @ExceptionHandler(Exception.class)
    public ErrorResponse handleException(Exception e) {
        log.error("Exception is occured", e);

        return new ErrorResponse(
                INTERNAL_SERVER_ERROR,
                INTERNAL_SERVER_ERROR.getDescription()
        );
    }
}

 

'Spring' 카테고리의 다른 글

[Spring] JUnit과 Mokito/단위 테스트 코드  (0) 2022.10.25
[Spring] Lombok  (0) 2022.10.24
[Spring] Spring MVC - 필터와 인터셉터  (0) 2022.10.24
[Spring] Spring MVC - HTTP 요청과 응답  (0) 2022.10.23
[Spring] Validation/Data Binding  (0) 2022.10.23