Spring MVC - 예외처리

박근수·2024년 2월 25일
0

Spring

목록 보기
9/11

예외란?

프로그램이 예상치 못한 상황을 만났을 때 오류를 발생시키는 것 (throw new Exception())

일반적인 자바 프로그램이 예외를 처리하는 방법

try{
	doSomething();
}catch (Exception e){
	lof.error("Exception is occurred", e);
    handleException(e);
    //throw e;
}

스프링 MVC에서 예외를 처리하는 방법 (REST API)

@ExceptionHandler
  • 컨트롤러 기반 예외 처리
  • HTTP Status code를 변경하는 법
    • @RequestStatus
    • ResponseEntity 활용
  • 예외처리 우선순위
    1. 해당 Exception이 정확히 지정된 Handler
    2. 해당 Exception의 부모 예외 Handler
    3. 이도 저도 아니면 그냥 Exception(모든 예외의 부모)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(IllegalAccessException.class)
    public String handleIllegalAccessException(
            IllegalAccessException e){
        log.error("IllegalAccessException is occurred.", e);
        return "INVALID_ACCESS";
    }
@RestControllerAdvice
  • 애플리케이션의 전역적 예외 처리
  • @ControllerAdvice랑 차이
    • ControllerAdvice : 기본적으로 view를 응답하는 방식
    • RestControllerAdvice : REST API용으로 객체를 응답하는 방식(JSON)
  • 스프링 백엔드 개발에서 현재 가장 많이 활용되는 기술(일반적인 예외 및 응답처리)
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler{
	@ResponseStatus(value = HttpStatus.FORBIDDEN)
    @ExceptionHandler(IllegalAccessException.class)
    public ErrorResponse handleIllegalAccessException(IllegalAccessException e){
    log error("Illegal Exception : ", e);
    
    return new ErrorResponse("ACCESS_DENIED", "Illegal Exeption ocuurred,");
    }
}
profile
개발블로그

0개의 댓글