ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring MVC - 예외처리
    Spring/Spring MVC 2022. 1. 4. 00:07
    반응형

    예외처리

    • 프로그램 실행 중 오류가 발생되면 프로그램이 중단되고, 오류 페이지가 나타나게 된다.
    • Java에서는 이를 방지하기 위해 오류 처리라는 개념이 있다.
    • 오류 발생 시 보여줄 JSP를 만들고 오류가 발생하면 이 JSP를 응답 결과로 브라우저에 전달한다.
    • Exception Handler는 각 Controller에서 처리하는 Exception Handler와 해당 Controller에 없는
      예외 처리를 위해 Global Exception Handler를 만든다.
    • Controller에도 특정 예외처리가 있고 controllerAdvice에도 특정 예외처리가 있다면  Controller에
      있는 예외처리가 우선 처리된다.

     


     

    Exception Handler
    • 각 Contoller에 발생 가능한 예외들을 Exception Handler를 통해 정의해준다.
    • Exception Handler를 통해 반환되는 JSP를 응답 결과로 브라우저에 전달해준다.
    • @ExceptionHandler는 Controller 마다 만들어 줘야 한다.

    testController.java 

    @Controller
    public class testContoller {
    
    	@GetMapping("/test1")
    	public String test1(Model model) {
    		int [] arr1 = {10, 20, 30};
    		// ArrayIndexOutOfBoundsException 에러 발생
    		model.addAttribute("arr1", arr1[10]);
    		
    		// 해당 Exception Handler가 Controller에 없기 떄문에 Global Exception Handler로 처리
    		ArrayList<String > list = null;
    		list.add("문자열");
    
    		return "test1";
    	}
    	// ArrayIndexOutOfBoundsException이 발생하면 오류페이지가 나타나지 않고
    	// 실행되는 메소드
    	@ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    	public String exception1() {
    		return "error1";
    	}
    }
    int [] arr1 = {10, 20, 30};
    model.addAttribute("arr1", arr1[10]);
     - ArrayIndexOutOfBoundsException 에러 발생
     - 해당 Controller에 있는 Exception Handler로 이동

    ArrayList<String> list = null;
    list.add("문자열");
     - NullPointerException 에러 발생
     - 해당 Controller에 예외 처리하는 Exception Handler가 없으므로 Global Exception Handler로 이동

    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    public String exception1() {
          return "error1";
    }
     - ArrayIndexOutOfBoundsException 에러 발생 시 error1.jsp를 응답 결과로 브라우저에 보냄

     

    Global Exception Handler
    • Controller 마다 중복되는 예외처리를 할 때 한 번에 정의하여 사용할 수 있다.
    • Controller에 예외 처리하는 Exception Handler가 없을 경우 Global Exception Handler로 이동하여 
      관련된 처리를 해주게 된다.

    해당 GlobalExceptionHandler를 사용하기 위해 예외처리해주는 패키지를

    @ComponentScan("kr.co.exception")를 ServletAppContext.java에 추가해준다.

     

    GlobalExceptionHandler.java 

    @ControllerAdvice
    public class GlobalExceptionHandler extends RuntimeException{
    
    	// Controller의 ExceptionHandler가 우선 순위를 갖고 있다.
    	@ExceptionHandler(NullPointerException.class)
    	public String handleException() {
    		return "error2";
    	}
    }
    public class GlobalExceptionHandler extends RuntimeException{
     - RuntimeException을 상속받아야 한다.

    @ControllerAdvice

     - @Controller나 @RestController에서 발생한 예외를 한 곳에서 관리하고
      처리할 수 있게 도와주는 어노테이션이다. 

     

     

     

    반응형

    댓글

Designed by Tistory.