2-27 예외처리(1) - 실습

서현우·2022년 5월 28일
0

복습

목록 보기
19/34

ExceptionController.java
글로벌 캐쳐 없이 예외 처리 함.

package com.fastcampus.ch2;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ExceptionController {
	@ExceptionHandler(NullPointerException.class)
	public String catcher2(Exception ex, Model m) {
		m.addAttribute("ex", ex);
		return "error";
	}
	
	@ExceptionHandler(Exception.class)
	public String catcher(Exception ex, Model m) {
		m.addAttribute("ex",ex);
		System.out.println("m="+m); //아래 모델과는 다른 객체이므로 메세지 전송 안됨.
		return "error";
	}
	
	
	@RequestMapping("/ex")
	public String main(Model m) throws Exception {
			//위의 @ExceptionHandler의 모델과는 전혀 다른 모델 객체를 사용.
			m.addAttribute("msg", "message from ExceptionController.main()");
			throw new Exception("예외가 발생했습니다.");
		
	}
	@RequestMapping("/ex2")
	public String main2() throws Exception {
		
			throw new NullPointerException("예외가 발생했습니다.");
	}		
}

ExceptionController.java
GlobalCatcher를 만들어서 예외처리 하게 함.

package com.fastcampus.ch2;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ExceptionController2 {
		
	@RequestMapping("/ex3")
	public String main() throws Exception {
		
			throw new Exception("예외가 발생했습니다.");
		
	}
	@RequestMapping("/ex4")
	public String main2() throws Exception {
		
			throw new NullPointerException("예외가 발생했습니다.");
	}		
}

GlobalCatcher.java
글로벌 캐쳐 클래스를 만들어서
@ControllerAdvice를 붙여서 같은 패키지, 다른 패키지 또는 모든 패키지에 적용 가능.

package com.fastcampus.ch2;

import java.io.FileNotFoundException;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

//@ControllerAdvice("com.fastcampus.ch2") //패키지를 적으면 그 패키지에만 적용
@ControllerAdvice //패키지를 안 적으면 모든 패키지에 적용
public class GlobalCatcher {
	@ExceptionHandler({NullPointerException.class, FileNotFoundException.class})
	public String catcher2(Exception ex, Model m) {
		m.addAttribute("ex", ex);
		return "error"; //jsp
	}
	
	@ExceptionHandler(Exception.class)
	public String catcher(Exception ex, Model m) {
		m.addAttribute("ex",ex);
		return "error";
	}
}
profile
안녕하세요!!

0개의 댓글