본문 바로가기
카테고리 없음

[Springboot] BindException 발생 시 ExceptionHandler 처리

Request Param으로 LocalDateTime을 받으려고 했으나 LocalDateTime 타입에 맞지 않은 값이 들어왔다.

 

// 받으려고 한 정보
data class OrderSearchCondition(
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    val startDate: LocalDateTime? = LocalDateTime.now().minusMonths(1).removeTime(),
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    val endDate: LocalDateTime? = LocalDateTime.now().removeTime(),

    val status: String? = null,
)

위 처럼 yyyy-MM-dd HH:mm:ss 포맷으로 받으려고 했으나 yyyy-MM-dd 형식으로 왔을 때 BindException이 발생했고 해당 값을 알려주기 위해 ExceptionHandler를 추가했다.

 

@ExceptionHandler(BindException::class)
fun beanPropertyBindingResult(ex: BindException): ResponseEntity<String>{
    val codes = ArrayList<String>()

    if(ex.bindingResult.hasErrors()){
        ex.bindingResult.fieldErrors.forEach { fieldError ->
            logger.error("filedError : ${fieldError.field}")
            codes.add(fieldError.field)
        }
    }

    return ResponseEntity<String>(
        "요청 매개변수가 잘못되었습니다. 매개변수를 확인해주세요. 개수 : ${codes.size}, 대상 : ${codes.joinToString(",")}",
        HttpStatus.BAD_REQUEST
    )
}