Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개(발)린이

Spring(예외처리) 본문

Spring

Spring(예외처리)

불도정 2023. 4. 27. 15:52

오늘 해볼 것은 예외처리이다.

 

별다른건 아니고 에러가 났을 경우 에러 페이지로 이동하는 기능을 구현 해볼거다

 

- 스프링 예외 처리 방법(3가지, 중복 사용가능)

스프링 예외 처리 방법 (3가지, 중복 사용 가능)
 
1 순위 : 메소드 별로 외처리 (try-catch / throws)
 
 2 순위 : 하나의 컨트롤러에서 발생하는 예외를 모아서 처리
 -> @ExceptionHandler (메소드에 작성)
 
 3 순위 : 전역(웹 애플리케이션)에서 발생하는 예외를 모아서 처리
 -> @ControllerAdvice(클래스에 작성)
 

2순위 3순위를 구현해 보자

 

먼저 2순위이다.

우선 error페이지 jsp이다.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Error</title>
    <style>
        #error-container{
            width: 800px;
            height: 300px;
            text-align: center;
            
            position: absolute;
            top : 0; bottom: 0; left: 0; right: 0;
            margin: auto;
        }
        
        #error-container > h1{ margin-bottom: 50px; }

        .error-cnotent-title{
        	text-align: left;
            font-weight: bold;
        }
        
        #btn-area{ text-align: center;  }

    </style>
</head>
<body>

    <div id="error-container">
        <h1>${requestScope.errorMessage}</h1>
        
        <span class="error-cnotent-title"> 발생한 예외 : ${e}</span>
        <p>
        	자세한 문제 원인은 이클립스 콘솔을 확인해주세요.
        </p>
        
        <div id="btn-area">
        	<a href="${pageContext.servletContext.contextPath}">메인 페이지</a>
        	
        	<button onclick="history.back()">뒤로 가기</button>
        </div>
    </div>
    
    
   
    
    
</body>
</html>

 

다음은 메소드이다.

MemberController 클래스 최 하단에 작성해준다.

 

@ExceptionHandler(Exception.class)
	public String exceptionHandler(Exception e, Model model) {
		e.printStackTrace();
		
        model.addAttribute("errorMessage", "서비스 이용 중 문제가 발생했습니다.");
		model.addAttribute("e", e);
        
		return "common/error";
	}

2순위의 단점은 MemberController에서 발생한 예외만 처리가 가능하다는 것.

 

다음은 3순위, 전역에서 발생하는 예외 처리하는 클래스를 만들어보겠다.

 

멤버 컨트롤러와 같은 패키지에 ExceptionController 클래스를 만들어준다

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

@ControllerAdvice
public class ExceptionController {
	
	@ExceptionHandler(Exception.class)
	public String exceptionHandler(Exception e, Model model) {
		e.printStackTrace();
		
		model.addAttribute("errorMessage", "서비스 이용 중 문제가 발생했습니다.");
		model.addAttribute("e", e);
		
		return "common/error";
	}
}

클래스에 @ControllerAdvice만 삽입하면 끝

 

실험해보자

member-mapper.xml에 sql문 마지막에 세미콜론을 입력해 의도적으로 예외를 발생시켜보았다.

 

에러페이지가 잘 작동되었다!

'Spring' 카테고리의 다른 글

Spring 게시판  (0) 2023.05.01
String(my page)  (0) 2023.05.01
Spring(회원 가입 DB 저장 - 2)  (0) 2023.04.26
Spring(회원 가입 - DB저장)  (0) 2023.04.26
Spring(회원가입 - 이메일 중복 체크)  (0) 2023.04.26