본문 바로가기
Java Web/Spring Boot

[Spring Code] 사용자 정의 예외 클래스와 에러 페이지

by 스응 2023. 4. 19.
728x90
728x90

#  관련 포스팅

  - 예외 처리 : https://young0105.tistory.com/196

 


#  사용자 정의 예외 클래스

  - src/main/java/메인패키지.handler.exception 아래에 생성

 

1
2
3
4
5
6
7
8
9
10
11
12
@Getter
public class CustomException extends RuntimeException {
    
    private HttpStatus status;
 
    public CustomPageException(String message, HttpStatus status) {
        // RuntimeException 클래스의 String 매개변수를 받는 생성자
        super(message);
        this.status = status;
    }
 
}
cs

 

 


유형 1) 예외 발생 시, 에러 페이지를 반환하기

#  @ControllerAdvice

  - src/main/java/메인패키지.handler 아래에 생성

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@ControllerAdvice
public class MyPageExceptionHandler {
 
    // 사용자 정의 클래스 활용
    @ExceptionHandler(CustomException.class)
    public ModelAndView handleRuntimePageException(CustomPageException e) {
        
        // 매개변수에 생성해둔 에러 페이지의 경로 및 파일명 기술
        ModelAndView modelAndView = new ModelAndView("errorPage"); // yml에 기술해서, 경로, .jsp 생략
        
        // ModelAndView에는 값을 담아 보낼 수 있음
        modelAndView.addObject("statusCode", HttpStatus.NOT_FOUND.value()); // .value()하면 상태 코드 숫자 반환
        modelAndView.addObject("message", e.getMessage());
 
        return modelAndView;        
 
    }
 
}
cs

 

#  에러 페이지

  - src/main/webapp/WEB-INF/view 아래에 생성

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>  <!-- 이걸 지정해야 에러 페이지가 됨 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>에러 페이지</h1>
    <p>에러 코드 : ${statusCode}</p>
    <p>에러 메세지 : ${message}</p>
</body>
</html>
cs

 

#  사용하기

  - if 문에서 특정 조건에 해당하면 에러 페이지를 반환하는 방식으로 활용할 수 있음

 

1
2
3
if (조건식) {
    throw new CustomException("페이지를 찾을 수 없습니다.", HttpStatus.NOT_FOUND);
}
cs

 

 

반응형

유형 2) 예외 발생 시, 경고 창을 반환하고 이전 페이지로 돌아가기

#  @RestControllerAdvice

  - src/main/java/메인패키지.handler 아래에 생성

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RestControllerAdvice // IoC 대상 + AoP 기반
public class MyRestFullExceptionHandler {
 
    // 사용자 정의 예외 클래스 활용
    @ExceptionHandler(CustomRestfullException.class)
    public String basicException(CustomRestfullException e) {
        StringBuffer sb = new StringBuffer();
        sb.append("<script>");
        sb.append("alert('"+ e.getMessage() +"'); "); // 예외 클래스의 매개변수로 받은 message가 출력됨
        sb.append("history.back();"); // 이전 페이지로 돌아감
        sb.append("</script>");
        return sb.toString();
    }
 
}
cs

 

#  사용하기

1
2
3
4
if (조건식) {
    throw new CustomException("잘못된 요청입니다.", HttpStatus.BAD_REQUEST);
}
 
cs

 

320x100
반응형

댓글