예외 처리를 위한 메서드를 작성하고 @ExceptionHandler를 붙인다.
@ExceptionHandler(처리할 예외)
public String catcher(처리할 예외, Model m) { // 예외 처리 메서드, try-catch 역할을 한다.
m.addAttribute("ex", ex);
return "error";
}
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(Exception.class)
public String catcher(Exception ex, Model m) {
m.addAttribute("ex", ex);
return "error";
}
@ExceptionHandler(NullPointerException.class)
public String catcher2(NullPointerException ex, Model m) {
m.addAttribute("ex", ex);
return "error";
}
@RequestMapping("/ex")
public String main() throws Exception{
throw new Exception("예외가 발생했습니다.");
}
@RequestMapping("/ex2")
public String main2() throws Exception{
throw new NullPointerException("예외가 발생했습니다.");
}
}
@ControlleAdvice로 전역 예외 처리 클래스 작성 가능(패키지 지정 가능)
예외 처리 메서드가 중복된 경우, 컨트롤러 내의 예외 처리 메서드가 우선된다.
응답 메시지의 상태 코드를 변경할 때 사용