Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

Exception Resolver, 예외 페이지 본문

Project/블로그 게시판 만들기

Exception Resolver, 예외 페이지

Seung__ 2021. 10. 21. 22:51

1. ExceptionResolver


  • 예외가 터지면 WAS까지 올라가서 500이 터진다.
  • client가 허가되지 않은? 여튼 client가 잘못한경우도 exception이 발생하는 경우 500으로 처리된다.
  • 하지만 이와같이 Client가 잘못 요청한 경우는 400으로 처리한는게 맞는 것 같다. 
  • 저번에 Naver API를 사용하면서 된통 당했었다 ㅋㅋㅋ 500으로 계속 응답이와서 서버 문제인 줄 알았떠니,
  • 내가 잘못한 경우였다.. ㅜ
  • 여튼 그래서 Client에서 잘못된 요청을 하는 경우 IllegalArgumentException을 터트릴 계획이다.
  • IllegalArgumentException이 발생하는 경우는 500이 아니라 400으로 응답할 것이다.
  • ExceptionResovler를 사용하면 예외 발생시 Resolver에서 예외를 처리하는데, 
  • 이 때 Resolver에서 예외를 먹어머리고 500아닌 400으로 응답을 줄 수 있다.
 

[API예외] HandlerExceptionResolver

예외가 발생해서 서블릿을 넘어 WAS까지 예외가 전달되면 HTTP 상태코드가 500으로 처리된다. 발생하는 예외에 따라서 400, 404 등등 다른 상태코드로 처리하고 싶은데? 오류 메시지, 형식등을 AP

bsh-developer.tistory.com

 

2. ExceptionResolver


  • 코드는 간단하다.
  • IllegalArgumentException이 발생하면 응답으로 400을 지정하고
  • 새로운 ModelAndView를 return한다. 이렇게 되면 예외는 여기서 처리하고 정상적인 흐름으로 진행된다.
@Slf4j
public class MyExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        if (ex instanceof IllegalArgumentException){
            log.info("Resolve IllegalArgumentException as 400");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return new ModelAndView();
        }

        return null;
    }
}

 

 

3. ExceptionResolver 등록


  • 등록은 진짜 간단 ㅋㅋㅋㅋㅋ
@Configuration
@RequiredArgsConstructor
public class ExceptionResolverConfig implements WebMvcConfigurer{

    @Override
    public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {

        resolvers.add(new MyExceptionResolver());
    }
}

 

 

4. 결과


  • 가장 간단한 경우로   page번호를 음수를 넣으면 IllegalArgumentException이 터진다.

 

 

 

5. Test


  • 참고로 비정상적인 접근은 IllegalAccessException으로 처리하며, 400으로 return.
    @Test
    void 음수_페이지_번호() throws Exception {
        mockMvc.perform(
                get("/posts?page=-1"))
                .andExpect(status().is4xxClientError());
    }

    @Test
    void 양수_범위_벗어난_페이지_번호() throws Exception {
        /**
         * 테스트 데이터 2, 한 페이지 10개 출력.
         * 페이지 수는 1
         */
        mockMvc.perform(
                get("/posts?page=10"))
                .andExpect(status().is4xxClientError());
    }
    
    @Test
    void 비로그인_글수정_시도_GET() throws Exception {
        Post post1 = postService.findPostByTitle("test1");

        mockMvc.perform(get("/posts/edit/{id}", post1.getId()))
                .andExpect(status().is4xxClientError());
    }


    @Test
    void 비로그인_글수정_시도_POST() throws Exception {
        Post post1 = postService.findPostByTitle("test1");

        mockMvc.perform(post("/posts/edit/{id}", post1.getId()))
                .andExpect(status().is4xxClientError());
    }

 

 

 

6. 앞으로


  • est용 data 서버시작할 때 DB에 올리기
  • Listener
    • createdAt, updatedAt등
  • 게시글에 작성자 표시
  • view 정리
  • 게시글 검색
    • 검색 옵션 추가 : 작성자, 제목 구분
  • 영속성 전이 설정
    • 게시글 삭제
    • 회원 탈퇴
  • 댓글 삭제 버튼
  • 글 수정 기능 추가
  • 대댓글
  • 검증 & 예외처리
    • 회원 가입시 필수 정보 지정.
    • 특수문자, 공백 검증 등(email  형식?)
    • Spring제공 Validator로 변경.
  • 인증처리
    • 로그인한 사용자만 글 & 댓글 작성 가능.
    • 본인이 작성한 글, 댓글만 수정/삭제 가능
    • 관리자는 모든 권한
  • 오류 화면, 예외처리
  • 페이징 처리
    • 버그 수정
  • 컬렉션 조회 최적화

 

7. GitHub: 211021 Exception


 

GitHub - bsh6463/blog

Contribute to bsh6463/blog development by creating an account on GitHub.

github.com

 

'Project > 블로그 게시판 만들기' 카테고리의 다른 글

블로그 만들기 결과  (0) 2021.10.22
id 생성전략 변경  (0) 2021.10.22
Paging처리  (0) 2021.10.21
비로그인 사용자 글 등록/삭제/수정 test  (0) 2021.10.19
@AutoConfigureMockMvc, PostController Test  (0) 2021.10.19
Comments