본문 바로가기

Spring

"Spring에서는 어떻게 예외처리 하죠?"

<자바>

try ~ catch

throws

<JSP>

error page

<web.xml>

<error-page>


<Spring>


Advice란? 

출처: https://blog.naver.com/kuhong1/8648081


AOP, Cross-cutting concern 구현한 코드를 Advice라고 하며, Primary concern 구현한 코드를 Code라고 부른다. Code와 Advice를 연결해주는 설정 정보를 Point-cut이라고 하며, 둘을 조합해서 애플리케이션으로 완성하는 과정을 Weaving(조합)이라고 부른다.


Cross-cutting concern(횡단관심사): 다른 관심사에 영향을 미치는 프로그램의 애스펙트

예시) 의무기록 어플리케이션

핵심관심사: 색인화

횡단관심사: 로깅, 인증 

※ 로깅: 시스템 작동시 각종 정보 기록하는 것 (각종 정보 예시)기록 · 보존, 이용자의 습성조사 및 시스템 동작의 분석 등 


<CommonExceptionAdvice.java>

package com.encore.control;

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

@ControllerAdvice
public class CommonExceptionAdvice {
	private static final Logger logger = LoggerFactory.getLogger(CommonExceptionAdvice.class);
	@ExceptionHandler(Exception.class)
	public String common(Exception e, Model model) {
		logger.info("모델객체="+model);
		logger.info(e.toString()); //에러메시지를 (서버콘솔) 화면에 출력
		model.addAttribute("exception", e);
		return "error_common"; //응답페이지
	}
}

 

<error_common.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<%-- error_common.jsp --%>
<body>
	<h4>${exception.getMessage()}</h4>
	<ul>
		<c:forEach items="${exception.getMessage()}" var="stack">
			<li>${stack.toString()}</li>
		</c:forEach>
	</ul>
</body>
</html>



※ Advanced Rest Client를 이용해서 Ajax 뷰를 대신해 데이터 값이 제대로 들어갔는지 요청해줄 때

@ControllerAdvice를 주석처리 안 해 놓으면

@Controller 에서

@RequestBody를 해주었기 때문에 JSON으로 값을 넘겨주어야 한다


파라미터에는 값을 넘겨주지만 application/json으로 값을 넣어주지 않아서 에러가 나게 된다




에러를 예상했는데 에러 페이지가 나온다 주석처리를 안 해주었기 때문에 응답페이지로 에러 페이지가 나오게 된 것이다. 따라서 200 OK 표시가 나온 것!! 

@ControllerAdvice를 주석처리 해주면

415 Error가 나온다