Spring Boot 에러 페이지 처리

송지윤·2024년 5월 17일

Spring Framework

목록 보기
60/65

HTTP 응답 상태 코드

400 : 잘못된 요청 (Bad Request)

403 : 서버에서 외부 접근 거부 (Forbidden)

404 : 요청 주소를 찾을 수 없다 (Not Found)

405 : 허용되지 않은 메서드(요청방식) (Method Not Allowed)

500 : 서버 내부 오류 (Internal Server Error)

에러 페이지 처리

스프링 예외 처리 방법(우선 순위별로 작성)

  1. 메서드에서 직접 처리 (try-catch, throws)
  2. 컨트롤러 클래스에서 클래스 단위로 모아서 처리
    (@ExceptionHandler 어노테이션을 지닌 메서드를 작성)
  3. 별도로 클래스를 만들어서 프로젝트 단위로 모아서 처리
    (@ControllerAdvice 어노테이션을 지닌 클래스를 작성)

@ControllerAdvice

전역적 예외 처리

@ExceptionHandler(예외 종류)

예외 종류 : 메서드별로 처리할 예외를 지정

ex)
@ExceptionHandler(SQLException.class) - SQL 관련 예외만 처리
@ExceptionHandler(IOException.class) - 입출력 관련 예외만 처리
@ExceptionHandler(Exception.class) - 모든 예외 처리

404 에러 처리 방법

404.html

<body>

    <main class="container">

        <section class="error-number-container">
            <h1>404</h1>
        </section>

        <section class="error-message-container">

            <h1>페이지를 찾을 수 없습니다</h1>

            <p>페이지의 주소가 올바르지 않거나, 변경/삭제되어 이용할 수 없습니다.</p>

            <article class="btn-area">
                <a class="main-btn" href="/">메인 페이지로 이동</a>
            </article>
        </section>
    </main>
</body>

ExceptionController

@ControllerAdvice
public class ExceptionController {
	
	@ExceptionHandler(NoResourceFoundException.class)
	public String notFound() {
		return "error/404";
	}
}

프로젝트에 발생하는 모든 종류 에러 처리

500.html

<body>

    <main class="container">

        <section class="error-number-container">
            <h1>500</h1>
        </section>

        <section class="error-message-container">

            <h1>서버 내부 오류 발생</h1>

            <p th:text="|원인 : ${e}|">원인 : 예외 발생 원인 출력</p>

            <label for="detailOn">자세히 보기</label>
            <input type="radio" name="detail-toggle" id="detailOn" class="detailCheck">
            <div class="detail-container">
                <label for="detailOff">닫기</label>
                <input type="radio" name="detail-toggle" id="detailOff" class="detailCheck">
                
                <div class="detail-content">
                    <p th:each="t : ${e.getStackTrace()}" th:text="${t}"></p>
                </div>
            </div>
            
            
           
            <article class="btn-area">
                <a class="main-btn" href="/">메인 페이지로 이동</a>
            </article>
        </section>
    </main>
</body>

e를 실어서 보내줄거임

ExceptionController

예외 처리하는 메서드에서 사용 가능한 매개변수 (Controller 에서 사용하는 모든 매개변수 작성 가능)

	@ExceptionHandler(Exception.class)
	public String allExceptionHandler(Exception e, Model model) {
    	e.printStackTrace();
		model.addAttribute("e", e);
		return "error/500";
	}

mapper.xml 에서 로그인 sql 에 , 하나 찍어서 500 에러 발생 시킴

프로젝트 완성도를 높이기 위해서 필요함

0개의 댓글