Notice
Recent Posts
Recent Comments
Link
«   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
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

예외처리: Exception Handler 본문

인프런/[인프런] Kotlin으로 개발하는 Spring Boot Web MVC

예외처리: Exception Handler

Seung__ 2022. 4. 25. 23:22

1. ErrorResponse


다음과 같이 Error발생시 Response를 내려준다고 해보자.

data class ErrorResponse(

    @field:JsonProperty("result_code")
    var resultCode: String?=null,

    @field:JsonProperty("http_status")
    var httpStatus: String?=null,

    @field:JsonProperty("http_method")
    var httpMethod : String?= null,

    var message: String?=null,
    var path: String?=null,
    var timestamp: LocalDateTime?= null,
    var errors: MutableList<Error>? = mutableListOf()
)

data class Error(
    var field: String? =null,
    var message: String?= null,
    var value:Any? = null
)

 

 

2. 사용예시


다음과 같이 get 메서드는 name, age를 쿼리 파라미터로 받고, 검증을 통과했을 시 아래 로직이 실행된다.

 

아래에 HttpServletRequest는  Http요청 정보를 편리하게 사용할 수 있는 기능을 제공.

@RestController
@RequestMapping("/api/exception")
@Validated
class ExceptionApiController {

    @GetMapping("/hello")
    fun hello(){
        val list = mutableListOf<String>()
        val temp = list[0]
    }

    @GetMapping
    fun get(
        @NotBlank
        @Size(min=2, max=6)
        @RequestParam name: String,

        @Min(10)
        @RequestParam age: Int): String {

        println(name)
        println(age)

        return "$name $age"
    }

    @PostMapping
    fun post(@Valid @RequestBody userRequest: UserRequest): UserRequest {
        println(userRequest)
        return userRequest
    }

    @ExceptionHandler(value = [MethodArgumentNotValidException::class])
    fun methodArgumentNotValidException(e: MethodArgumentNotValidException, request:HttpServletRequest): ResponseEntity<ErrorResponse>? {
        val errors = mutableListOf<Error>()

        e.bindingResult.allErrors.forEach { errorObject ->
            val error = Error().apply {
                this.field = (errorObject as FieldError).field
                this.message = errorObject.defaultMessage
                this.value = errorObject.rejectedValue
            }

            errors.add(error)
        }

        //2. ErrorResponse
        val errorResponse = ErrorResponse().apply {
            this.resultCode = "FAIL"
            this.httpStatus = HttpStatus.BAD_REQUEST.value().toString()
            this.message = "요청에 에러가 발생했음."
            this.httpMethod = request.method
            this.path = request.requestURI.toString()
            this.timestamp = LocalDateTime.now()
            this.errors = errors

        }

        //3. ResponseEntity
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse)


    }

    @ExceptionHandler(value = [IndexOutOfBoundsException::class])
    fun indexOutOfBoundsException(e: IndexOutOfBoundsException): ResponseEntity<String>? {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Index Error")
    }


    @ExceptionHandler(value = [ConstraintViolationException::class])
    fun constraintViolationException(e: ConstraintViolationException, request: HttpServletRequest): ResponseEntity<ErrorResponse>? {
        //HTTP 요청 정보를 편리하게 사용할 수 있는 HttpServletRequest
        //request객체에서 원하는 정보 꺼내면 됨.

        //1. 에러 분석
        val errors = mutableListOf<Error>()

        e.constraintViolations.forEach{

            val error = Error().apply {
                //propertyPath의 마지막에 변수 이름이 있음.
                this.field = it.propertyPath.last().name
                this.message = it.message
                this.value = it.invalidValue
            }
            errors.add(error)
        }
        //2. ErrorResponse
        val errorResponse = ErrorResponse().apply {
            this.resultCode = "FAIL"
            this.httpStatus = HttpStatus.BAD_REQUEST.value().toString()
            this.message = "요청에 에러가 발생했음."
            this.httpMethod = request.method
            this.path = request.requestURI.toString()
            this.timestamp = LocalDateTime.now()
            this.errors = errors

        }

        //3. ResponseEntity
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse)
    }
}

 

 

3. GitHub


 

GitHub - bsh6463/KotlinSpring: GET

GET. Contribute to bsh6463/KotlinSpring development by creating an account on GitHub.

github.com

 

'인프런 > [인프런] Kotlin으로 개발하는 Spring Boot Web MVC' 카테고리의 다른 글

JUnit2  (0) 2022.04.29
JUnit Test  (0) 2022.04.26
예외처리: Controleller Advice  (0) 2022.04.25
JSR-380 Bean Validation : custom annotaion  (0) 2022.04.25
JSR-380 Bean Validation  (0) 2022.04.24
Comments