Error
- java.lang.Error 클래스의 하위 클래스
- 시스템이 비정상적인 상황인 경우, JVM에서 발생시킴
- 애플리케이션 코드에서 잡아도 대응할 수 있는 방법이 없다.
Exception(예외)
- 애플리케이션 코드에서 예외가 발생한 경우 사용됨
- 체크 예외, 언체크 예외로 구분됨.
- Check Exception(체크 예외)
- RuntimeException를 상속받지 않는 예외 클래스
- 복구 가능성이 있는 예외이므로, 반드시 예외를 처리하는 코드를 함께 작성해야 한다.
- 예외를 처리하지 않으면 컴파일 에러가 발생한다.
- IOException, SQLException 등이 있음.
- 실제 개발에서는 대부분 언체크 예외를 사용한다.
- Uncheck Exception(언체크 예외)
- RuntimeException를 상속받는 예외 클래스
- 복구 가능성이 없는 예외들이므로 컴파일러가 예외처리를 강제하지 않는다.
- NullPointerException, IllegalArgumentException 등이 있다.
ExceptionHandler
- 여러 컨트롤러에 대해 전역적으로 ExceptionHandler를 적용
- @ExceptionHandler(Exception)
- 예시 코드
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Object> handleIllegalArgument(IllegalArgumentException e) {
log.warn("handleIllegalArgument", e);
ErrorCode errorCode = CommonErrorCode.INVALID_PARAMETER;
return handleExceptionInternal(errorCode, e.getMessage());
}
private ResponseEntity<Object> handleExceptionInternal(ErrorCode errorCode, String message) {
return ResponseEntity.status(errorCode.getHttpStatus())
.body(makeErrorResponse(errorCode, message));
}
@ExceptionHandler({IllegalArgumentException.class})
- 모든 IllegalArgumentException에 대해 처리하는 ExceptionHandler
handleExceptionInternal(ErrorCode, Message)
가ResponseEntity<Object>
를 생성하여 반환한다.- ResponseEntity란?
HttpEntity
를 상속받는 HTTP 응답 데이터 클래스- 구조
- HttpStatus
- HttpHeaders
- HttpBody
- 예외 처리의 우선 순위
- 예외 처리의 우선순위는 메서드의 시그니처를 기반으로 결정, 더 구체적인 예외에 대한 처리가 우선됨
- 예를 들어,
@ExceptionHandler(Exception.class) 와 @ExceptionHandler(RuntimeException.class)
가 동시에 존재할 때, 런타임 예외가 발생하면@ExceptionHandler(RuntimeException.class)
가 먼저 호출됨
Share article