메서드 앞에 @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("예외가 발생했습니다.");
}
}
@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";
}
}