티스토리 뷰

Spring

Spring - Exception

0307kjb 2022. 1. 21. 19:28

Exception은 중요한 로직의 구성요소 중 하나다.

로직을 처리하는 도중 사용자 에러, 치명적인 에러에 Exception을 부여하여 로직을 깔끔하게 한다.

Spring에서 이러한 부분을 고려하여 여러가지 어노테이션을 가지고 있다.

 

@RestControllerAdvice
public class RestaurantControllerAdvice {

    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(RestaurantNotFoundException.class)
    public String restaurantNotFound(){
        return "{}";
    }
}
/*
@RestControllerAdvice은 Spring에서 ExceptionHanlder를 정의한 목록을 가지게 한다.
이곳에서 정의한 Exception들을 처리하는 것이다.

@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(RestaurantNotFoundException.class)

@ResponseBody를 한 이유는 웹 응답 시 Exception을 반환하기 위함.
@ResponseStatus(HTTP_ERROR)의 경우에는 현재 상태를 알려준다.(여기선 Not_Found)
@ExceptionHandler(UserDefinedExceptionClass.class)는 말 그대로 유저가 정의한 ExceptionClass이다.

*/

ControllerTest>>

@Test
public void getInValidRestaurant() throws Exception {
    given(restaurantService.getRestaurant(404L)).willThrow(new RestaurantNotFoundException(404L));

    mvc.perform(get("/restaurants/404")).andExpect(status().isNotFound())
            .andExpect(content().string(containsString("{}")));
}

ServiceTest>>

@Test
public void getInValidRestaurant(){
    assertThrows(RestaurantNotFoundException.class, () -> {
        Restaurant restaurant = restaurantService.getRestaurant(404L);
    });
}

/*
여기서, junit5 assertThrows를 사용하고
junit4의 경우 @Test(expected = RestaurantNotFoundException.class)를 사용한다.
*/

 

 

'Spring' 카테고리의 다른 글

Java, Mybatis, Oracle 연동 코드  (0) 2022.05.29
Spring - <JSON> data patch  (0) 2022.01.22
Spring - Validation  (0) 2022.01.21
JPA 활용.  (0) 2022.01.21
Spring5 , Mockito 관련 간단 정리.  (0) 2022.01.13
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   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
글 보관함