프로젝트

[Kotlin 토이프로젝트] CRUD 별 예외 처리

sian han 2022. 11. 18. 14:30

https://github.com/HAN-SEOHYUN/movie-api

CRUD 작성 기본흐름 : Service => ServiceIml => Resource

 

Create

▶ ServiceImpl

It has problem. Because it has expecting a Movie.

문제가 있다. save() 는 Movie 객체가 인자로 들어가야한다. 

 

So use a Mapper class (Movie Mapper Class)

그래서 ~ 만들어 둔 Mapper 클래스를 사용할거다. (Mapper 클래스는 DTO / Entity 간 변환을 위해 만들었다) 

 

And the method have to return the new entity (Whenever we creating or updating, we need updated object)

그리고 createMovie() 는 새로운 Entity 를 리턴해야한다.

 

 

위 문제를 고려해 createMovie() 코드를 바꿨다. 

Still has a problem.

When i create a new movieDTO, the entity add id automatically.

새로운 DTO 객체를 만들면, id 가 자동적으로 추가되어야 한다.

If i pass a DTO as above, It will have no id.

위의 코드로는 id 를 가질 수 없다. 

 

So created a new object.

 

 

▶ Resource

컨트롤러에서 API 를 디자인 하고

 

POSTMAN 을 통해 API 테스트를 했는데, BAD_REQUEST 가 응답되었다.

 

Default message saying that it doesn't know how to map the the values of this DTO.

I passed values in the request body.How spring will know how to get the value ? 

Add a @RequestBody annotation.

이제 의도한대로 작동하는 걸 확인할 수 있다. 

 

 

Expected Exception : How will we know that if the id is there or not ?

해당 예외에 대한 처리 과정은 포스트로 정리했다. 

[Kotlin 프로젝트] Handling Exceptions (tistory.com)

 

[Kotlin 프로젝트] Handling Exceptions

※ Handling Exceptions Exception 을 각각 설명하는 것이 아닌, 프로젝트를 진행하면서 어떤 과정에서 예외처리가 필요한 상황이 발생했는지, 어떻게 예외를 처리했는지, 또 예외 처리 과정을 어떻게 dev

feelfreetothink.tistory.com

 

 

 

 

Get : 전체 리스트 가져오기

JPA 에서 제공하는 findAll() 메서드는 Iterable<> 을 반환하기 때문에

getAllMovies 라는 메서드를 만들었다.

 

ServiceImpl

Expected Exception : 저장된 값이 없음

  override fun getMovies(): List<MovieDTO> {
        val movies = movieRepository.getAllMovies()

        if(movies.isEmpty())
            throw MovieException("List of movies is empty.")

        return movies.map{
            movieMapper.fromEntity(it)
        }
    }

저장된 값이 없을 예외를 생각해서 MovieException 추가함.

 

그리고 MoviceException 클래스를 만들었으니

createMovie 메서드를 아래와 같이 리팩토링 할 수 있다.

 

 

 

 

 

Get : findById()

Expected Exception : id 가 입력되지 않음

  override fun getMovie(id: Int): MovieDTO {
        val optionalMovie = movieRepository.findById(id)
        val movie = optionalMovie.orElseThrow{MovieException("Movie with id $id is not present") }
        return movieMapper.fromEntity(movie)
    }

JPA 의 findById() 는 optional 객체를 리턴하기 때문에 orElseThrow(MovieException) 

 

 

 

 

PUT : update object

Expected Exception : 업데이트 할 엔티티가 존재하지 않음

throw MovieException

 

Expected Exception : Value 를 모두 send 하지 않는다면 ? 

ex ) rating 을 제외한 값을 PUT request 로 보내면, rating 은 default value (0.0) 로 업데이트 된다. 

ex ) name을 제외한 값을 PUT request 로 보내면, bad request 가 응답된다. => name 은 nullable 이 아니기 때문

 

= > DTO data class Name 멤버변수에 default value 를 주고

ServiceImpl updateMovie 메서드에서 예외 처리

if(movieDTO.rating == 0.0 || movieDTO.name == "Default movie")
            throw MovieException("Complete movie object is expected")
            //rating 이나 name 에 값을 입력하지 않으면 MovieException 예외처리

 

 

 

 

DELETE : update object

Expected Exception : 삭제할 id 가 존재하지 않음

throw MovieException