예외 처리

 

ExceptionController.java

package com.fastcampus.app;

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

@Controller
public class ExceptionController {
	

	@RequestMapping("/ex")
	public String main() throws Exception{
		try {
			throw new Exception("예외가 발생했습니다.");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		}
	}
	
	@RequestMapping("/ex2")
	public String main2() throws Exception{
		try {
			throw new Exception("예외가 발생했습니다.");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		}
	}
}

 

error.jsp

<%@ page contentType="text/html;charset=utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
	<title>error.jsp</title>
</head>
<body>
<h1>예외가 발생했습니다.</h1>
발생한 예외 : ${ex}<br>
예외 메시지 : ${ex.message}<br>
<ol>
<c:forEach items="${ex.stackTrace}" var="i">
	<li>${i.toString()}</li>
</c:forEach>
</ol>
</body>
</html>

 

ExceptionHandler 추가

package com.fastcampus.app;

import org.springframework.stereotype.Controller;
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) {
		return "error";
	}

	@RequestMapping("/ex")
	public String main() throws Exception{
			throw new Exception("예외가 발생했습니다.");
	}
	
	@RequestMapping("/ex2")
	public String main2() throws Exception{
			throw new Exception("예외가 발생했습니다.");
	}
}

 

 

 

@ControllerAdvice

 

ExceptionHandler 는 같은 클래스 안에서만 동작한다

이를 해결하기 위해

@ControllerAdvice 를 사용해서 코드를 분리한다

 

@ControllerAdvice("com.jcy.ch2") : 설정한 패키지 안에서만 적용

@ContorllerAdvice : 모든 패키지에 적용

 

GlobalCatcher.java

package com.fastcampus.app;

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

@ControllerAdvice
public class GlobalCatcher {

	@ExceptionHandler(Exception.class)
	public String catcher(Exception ex, Model m) {
		m.addAttribute("ex", ex);
		return "error";
	}

}

 

'Spring > Ch2. Spring MVC' 카테고리의 다른 글

Spring MVC - DispatcherServlet  (0) 2022.09.23
Spring MVC - 예외 처리2  (0) 2022.09.22
Spring MVC - 로그인 페이지 만들기3  (1) 2022.09.21
Spring MVC - 로그인 페이지 만들기2  (0) 2022.09.20
Spring MVC - Session, 세션  (0) 2022.09.19
복사했습니다!