Hyunebee

예외처리 본문

카테고리 없음

예외처리

Hyunebee 2022. 6. 16. 21:06

REST API로 예외 처리하기

 

전역 처리시 @RestControllerAdvice, ControllerAdvice

 

@ExceptionHandler 컨트롤러 기반 예외 처리

 

HTTP Status code를 변경하는 방법

 @ResponseStatus

 ResponseEntity 활용

 

예외처리 우선순위

1. 해당 Exception이 정확히 지정된 Handler

2. 해당 Exception의 부모 예외 Handler

3. 이도 저도 아니면 그냥 Exception(모든 예외의 부모)

 

@ResponseStatus 사용

@ResponseStatus(value = HttpStatus.FORBIDDEN)
@ExceptionHandler(IllegalAccessException.class)
public ErrorResponse handleIllegalAccessException(IllegalAccessException e) {
    log.error("Illegal Exception : ", e);
    return new ErrorResponse("ACCESS_DENIED", "Illegal Exception occurred.");
}

 

 

ResponseEntity 사용

@ExceptionHandler(IllegalAccessException.class)
public ResponseEntity<ErrorResponse> handleIllegalAccessException(IllegalAccessException e) {
    log.error("Illegal Exception : ", e);
    return ResponseEntity
            .status(HttpStatus.FORBIDDEN)
            .header("header", "some value")
            .body(new ErrorResponse("ACCESS_DENIED", "Illegal Exception occurred."));
}