Day77 :) 예외처리

Nux·2022년 1월 7일
0

자바웹개발

목록 보기
91/105
post-thumbnail

스프링의 예외처리방법

  • Controller 레벨에서 처리
  • Global 레벨에서 처리

@ExceptionHandler

  • @Controller나 @RestController에서 발생한 예외를 하나의 메서드에서 처리해 줌
  • @Service나 @Repository에서는 사용 불가

Controller레벨의 예외처리

  • Controller에서 발생한 예외를 처리하는 기능

단일예외처리

@ExceptionHandler(value=처리할예외)
예제
@RestConroller
public class testRestController{

	@GetMapping("/exceptiontest")
    public String exception(){
    	throw new NullPointerException();
    }
    
    @ExceptionHandler(value=NullPointerException.class)
    public String exceptionHandle(NullPointerException e){
    	return "테스트1오류메세지";
    }
    
}
  • /exceptiontest에 접속 시, Exception Handler가 실행되어 return에 설정한 '테스트1오류메세지'가 출력됨

다중예외처리

@ExceptionHandler({처리할예외1, 처리할예외2})
@RestConroller
public class testRestController{

	@GetMapping("/exceptiontest1")
    public String exception(){
    	throw new NullPointerException();
    }
    
    @GetMapping("/exceptiontest2")
    public String exception(){
    	throw new RunTimeException();
    }
    
    @ExceptionHandler({NullPointerException.class, RunTimeException.class})
    public String exceptionHandle(NullPointerException e){
    	return "오류메세지";
    }
    
}
  • /exceptiontest 혹은 /exceptiontest2 접속 시, return에 설정한 '오류메세지'가 출력
  • 즉, 여러 Exception도 하나의 ExceptionHandler에서 처리 가능

Global레벨의 예외처리

  • 어플리케이션의 모든 컨트롤러의 예외처리를 가능하게 해줌
  • @ControllerAdvice 혹은 @RestControllerAdvice으로 예외처리용 클래스를 지정
    • @ControllerAdvice: 예외 발생 시, view(ErrorPage 등)로 이동시켜 처리
    • @RestControllerAdvice: 예외처리 메서드 내에서 Default값을 설정하고 이 값을 반환

ControllerAdvice

@ControllerAdvice
public class ExceptionTest1{

    @ExceptionHandler(value = RunTimeException.class)
    public String exceptionTest(RuntimeException ex) {
        return "/error";
    }
}

RestControllerAdvice

@RestControllerAdvice
public class ExceptionTest2{
	
    @ExceptionHandler({RuntimeException e, NullPointerException n})
    public String exceptionTest(Exception ex){
    	return "오류메세지 전달"
    }
    
}
  • 모든 Controller에서 RuntimeException, NullPointerException 발생 시, '오류메세지 전달'이 반환됨

0개의 댓글