20240703 (수) Hercute팀 - 메추리알(MCRA) 코딩 3일차

2024. 7. 3. 17:55TIL

오늘은 각종 서비스임플 부분 코드세부구현과 에러관련 처리를 담당하는 글로벌핸들러를 추가작성하였다.

package com.hercute.mcrabe.global.error.exception

import com.hercute.mcrabe.global.error.exception.dto.ErrorResponse
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import kotlin.io.AccessDeniedException

@RestControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler
    fun handleRuntimeException(e: RuntimeException): ResponseEntity<ErrorResponse> {
        e.printStackTrace()
        return ResponseEntity
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body(ErrorResponse(message = "Internal error"))
    }

    @ExceptionHandler(ModelNotFoundException::class)
    fun handleModelNotFoundException(e: ModelNotFoundException): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.NOT_FOUND)
            .body(ErrorResponse(e.message))
    }

    @ExceptionHandler(AccessDeniedException::class)
    fun handleAccessDeniedException(e: AccessDeniedException): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.NOT_FOUND)
            .body(ErrorResponse(e.message))
    }

    @ExceptionHandler(InvalidCredentialException::class)
    fun handleInvalidCredentialException(e: InvalidCredentialException): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.NOT_FOUND)
            .body(ErrorResponse(e.message))
    }

    @ExceptionHandler(IncorrectEmailPasswordException::class)
    fun handleIncorrectEmailPasswordException(e: IncorrectEmailPasswordException): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.UNAUTHORIZED)
            .body(ErrorResponse(e.message))
    }

    @ExceptionHandler(DateAlreadyPastException::class)
    fun handleDateAlreadyPastException(e: DateAlreadyPastException): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.BAD_REQUEST)
            .body(ErrorResponse(e.message))
    }

    @ExceptionHandler(AlreadyProcessedException::class)
    fun handleAlreadyProcessedException(e: AlreadyProcessedException): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.CONFLICT)
            .body(ErrorResponse(e.message))
    }

    @ExceptionHandler(CategoriesAlreadyExistException::class)
    fun handleCategoriesAlreadyExistException(e: CategoriesAlreadyExistException): ResponseEntity<ErrorResponse> {
        return ResponseEntity
            .status(HttpStatus.CONFLICT)
            .body(ErrorResponse(e.message))
    }
}

 

지난번 최종프로젝트 당시 예외처리를 너무 대충구현해놔서 프론트와의 연결때 오류가 났는데 어째서 오류가 난것인지 정확한 정보를 담고있질 않아서 쪼금 힘들었던 기억이 있다.
그래서 이번엔 예외처리를 더 꼼꼼하게 나눠서 구현해볼 예정이다.