사용할 클래스
1. ErrorCode : 모든 예외 케이스를 관리 하는 클래스.
2. ErrorResponse: JSON 형식으로 에러 응답 형식 작성.
3. Exception: 기본적으로 제공되는 Exception 이외에 추가할 Exception (예시로 EntityNotFound 그냥 구현).
4. GlobalExceptionHandler
- @ControllerAdvice: 프로젝트 전역에서 발생하는 Exception을 잡아주는 클래스
- @ExceptionHandler: 특정 Exception 을 지정해서 별도로 처리함.
1. ErrorCode를 Enum 클래스로 정의 해준다.
enum class ErrorCode(
private val status: Int,
private val errorCode: String,
private val message: String
) {
ENTITY_NOT_FOUND(404, "COM005", "Entity not found"),
}
2. exception 발생하면 응답하는 에러정보를 담고있는 클래스를 정의해준다.
data class ErrorResponse(
@field:JsonProperty("status")
private var status: Int,
@field:JsonProperty("message")
private var message: String,
@field:JsonProperty("code")
private var code: String
) {
constructor(errorCode: ErrorCode): this(errorCode.status, errorCode.message, errorCode.errorCode) {
}
}
3. 기본적으로 제공되는 Exception 이외에 추가할 Exception.
class EntityNotFoundException(
val errorCode: ErrorCode
): RuntimeException()
4. GlobalExceptionHandler
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(value = [RuntimeException::class]) //Runtime Error 터지면 아무거나 다잡음 -> 지정하지 않았는데 처리 되었음 -> Advice 명시 해주거나, 정말 표준적인 것만 처리
fun exception(e: RuntimeException): String {
return "Server Error"
}
@ExceptionHandler(EntityNotFoundException::class)
fun handleEntityNotFoundException(ex: EntityNotFoundException): ResponseEntity<ErrorResponse> {
val response = ErrorResponse(ex.errorCode)
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response)
}
}
5. 실제 API 호출 시 에러 테스트 확인
@Transactional
fun readPost(postId: Long): PostResDto {
val post: Post = postRepository.findByIdOrNull(postId)
?: throw EntityNotFoundException(ErrorCode.ENTITY_NOT_FOUND)
if(post.isDeleted == Y) {
return PostResDto(
id = null,
title = "삭제된 글 입니다.",
contents = "삭제된 내용입니다.",
isDeleted = Y,
view = null)
}
post.addView()
postRepository.save(post)
return PostResDto.entityToDto_v2(post)
}
이전에 글에서 구현하였던 프로젝트에서 서비스에 예외처리를 해주는 부분을 추가하였다.
이제 테스트를해보자!
DB에는 Id 가 10번인 글까지 존재한다. 존재하지 않는 Id가 100인 글을 호출해보자.
우리가 설정한 메세지대로 예외처리가 하는 모습을 볼 수 있다!!ㅎㅎ
이제 다른 파트와 더 좋은방법으로 협업을 해보자~~!
모든 소스코드는 GitHub에서 확인할 수 있습니다!!
https://github.com/Hyeongwon-up/Kotlin-Server-Side-Lab
GitHub - Hyeongwon-up/Kotlin-Server-Side-Lab: Springboot + Kotlin + JPA + Kotest 놀이터 😈
Springboot + Kotlin + JPA + Kotest 놀이터 😈. Contribute to Hyeongwon-up/Kotlin-Server-Side-Lab development by creating an account on GitHub.
github.com
'Spring > Kotlin' 카테고리의 다른 글
[Kotlin + Springboot + JPA] Entity 연관관계 (지연로딩, OrphanRemoval 확인) by Kotlin (0) | 2021.08.31 |
---|---|
[SpringBoot + Kotlin + JPA] 간단한 게시글 CRUD REST Api 구현. (0) | 2021.08.08 |
[Springboot + Kotlin] Slack 채널 메세지 전송 연동. (0) | 2021.08.06 |
[Kotlin + Springboot + Kotest] Kotest 알아보자. (0) | 2021.08.01 |
[Kotlin + Springboot + JPA] Entity 생성에 관하여. (0) | 2021.07.28 |