본문 바로가기
풀스택/Spring

spring에서의 예외처리

by woohyun22 2019. 2. 23.

https://github.com/jeongwoohyunn/mysite3-spring-


catch 비워두는게 잴안좋은거라고 배웠다. + 회피해서 다른데 넣어주는것도 안좋다.


한번에 처리하기



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@ControllerAdvice        //모든 오류가 여기로 몰린다.
public class GlobalExceptionHandler {
    
    private static final Log LOG = LogFactory.getLog( GlobalExceptionHandler.class );
    
    @ExceptionHandler(Exception.class)
    public ModelAndView handlerException(
            HttpServletRequest request,
            Exception e) {
        
        // 1. 로깅 작업
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        LOG.error(errors.toString());
        
        // 2. 시스템 오류 안내페이지 전환
        ModelAndView mav = new ModelAndView();
        mav.addObject("errors",    errors.toString());
        mav.setViewName("error/exception");
        
        return mav;
    }
}
cs


전체 exception은 여기로 오게한다.


web.xml에 넣어준다. 각각에 대한 jsp 파일을 만든다.


1
2
3
4
5
6
7
8
9
10
<!-- 공통 에러 페이지 -->
    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/views/error/404.jsp</location>
    </error-page>
 
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/views/error/500.jsp</location>
    </error-page>
cs


404.jsp


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"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>oops!</h1>
        <p>죄송합니다.<br>
        요청한 페이지를 찾을수 없습니다.<br>
        </p>
    </body>
</html>
cs


UserDaoException


1
2
3
4
5
6
7
8
9
10
11
public class UserDaoException extends RuntimeException {
    private static final long serialVersionUID = 1L;
 
    public UserDaoException() {
        super("UserDao 예외");
    }
    
    public UserDaoException(String message) {
        super(message);
    }
}
cs


728x90

'풀스택 > Spring' 카테고리의 다른 글

form validation 유효성검사 예제  (0) 2019.03.03
mysite3예제 user&guest 부분 servlet-jsp에서 spring로  (0) 2019.02.25
ViewResolver 설정  (0) 2019.02.23
spring html, css적용 안될때  (0) 2019.02.23
  (0) 2019.02.19

댓글