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

서현우·2022년 5월 15일
0

스프링의정석

목록 보기
27/85

ExceptionController.java

메서드 앞에 @ExceptionHandler를 붙여서 try-catch의 catch처럼 사용 가능. 단, 같은 클래스 내에서 사용.
@ExceptionHandler(Exception.class)
@ExceptionHandler({NullPointerException.class, FileNotFoundException.class})
catcher(Exception ex)
catcher(Exception ex, Model m)

package com.fastcampus.ch2;

import java.io.FileNotFoundException;

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, FileNotFoundException.class})
	public String catcher2(Exception ex, Model m) {
		m.addAttribute("ex", ex);
		return "error";
	}
	
	@ExceptionHandler(Exception.class)
	public String catcher(Exception ex, Model m) {
		System.out.println("catcher() in ExceptionController");
		System.out.println("m="+m);
		m.addAttribute("ex", ex);
		return "error";
	}
	
	
	@RequestMapping("/ex")
	public String main(Model m) throws Exception{
		m.addAttribute("msg", "message from ExceptionController.main");
		throw new Exception("예외가 발생했습니다.");	
	}
	
	@RequestMapping("/ex2")
	public String main2() throws Exception{
		throw new FileNotFoundException("예외가 발생했습니다.");	
	}
}

GlobalCatcher.java

@ControllerAdvice("com.fastcampus.ch2")
("")안의 패키지 안에서만 적용.
@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";
	}
	
	@ExceptionHandler(Exception.class)
	public String catcher(Exception ex, Model m) {
		m.addAttribute("ex", ex);
		return "error";
	}
}
profile
안녕하세요!!

0개의 댓글