예외 처리 흐름

오의석·2025년 1월 13일
1

현재 상황
extract 함수에 throws(예외 던지기)가 설정 안되어 있을 때,
상위 호출자에서 수신되는 과정에서 문제가 발생.

원인
@controlleradvice(글로벌 예외처리 어노테이션)에 의해 예외처리가 해당 클래스에서 처리됨


public List<TestVo> extract(TestVo testVo) {
	try {
		주요로직 //그러나 StrangeError가 발생
	} catch (Exception e) {
		throw e;
	}
}

상위 호출자:

try {
    testService.extract(testVo);
} catch (Exception e) {
    // 예외가 상위 호출자의 catch로 전달되어 처리됨
}

(RuntimeException의 하위 클래스인) StrangeError라 명시한 에러가 발생한 경우

  • StrangeError는 RuntimeException의 하위 클래스이므로 unchecked exception입니다.
  • 따라서, throws 선언에 명시하지 않아도 상위 호출자의 catch문에서 처리할 수 있습니다.
  • 그러나, throws 선언에 명시하지 않고 예외 처리 메서드(@ExceptionHandler)로 설정되어 있으면, 상위호출자의 Catch문에서 처리가 안됩니다. 예외 처리 메서드에서 처리됩니다.
    - @RestControllerAdvice(글로벌 예외 처리)로 전달되어 @ExceptionHandler에서 처리 됩니다.
  • 예외 처리 메서드(@ExceptionHandler)에 StrangeError가 아니라 그 상위 에러(ex : Exception.class)가 선언되었으면 그건 무시한다. (상위호출자의 catch문에서 처리된다.)

<EX 1>

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleAllExceptions(Exception ex) {
        return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

상위 호출자에서 처리 됨.


<EX 2>

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(StrangeError.class)
    public ResponseEntity<String> handleAllExceptions(StrangeError ex) {
        return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

글로벌 예외 처리됨


profile
끊임없이 나아가는 사람이 되어볼게요.

1개의 댓글

comment-user-thumbnail
2025년 1월 13일

우와 딱봐도 어려워보여요 짱이예요 최고다

답글 달기