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
관리 메뉴

개발자되기 프로젝트

예외처리: Controleller Advice 본문

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

예외처리: Controleller Advice

Seung__ 2022. 4. 25. 22:35

 

 

[API예외] @ControllerAdvice

@ExceptionHandler 를 사용해서 예외를 깔끔하게 처리할 수 있게 되었지만, 정상 코드와 예외 처리 코드가 하나의 컨트롤러에 섞여 있다. @ControllerAdvice 또는 @RestControllerAdvice 를 사용하면..

bsh-developer.tistory.com

@ControllerAdvice는 Controller에서 발생하는 Exception을 어떻게 처리할지 따로 분류해서 관리할 수 있도록 도와줌.

 

말 그대로 Controller에 대한 Advice이다.

 

아래와 같이 IndexOutOfBounds Exception이 무조건 발생하는 Controller가 있다고 해보자.

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

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

}

아무 것도 안하면 Spring은 500에러를 반환한다.

 

하지만 기본적인 Exception 처리가 아니라 별도로 Excpetion 처리 로직을 정학고 싶다.

 

이 때 사용할 수 있는 것이 @ControllerAdvice이다.

import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice

@RestControllerAdvice //RestController에 대한 Advice
class GlobalControllerAdvice {

    @ExceptionHandler(value = [RuntimeException::class])
    fun exception(e: RuntimeException): String {
        return "Server Error"
    }

    @ExceptionHandler(value = [IndexOutOfBoundsException::class])
    fun indexOutOfBoundsException(e: IndexOutOfBoundsException): String {
        return "Index Error"
    }
}

 

IndexOutOfBounds Exception의 경우 해당 Exception 발생 시 return에 있는 String을 응답 메시지 바디에 넣어서 응답한다.

 

이 때 발생한 Exception을 Advice에서 캐치했기 때문에 정상 흐름으로 바뀌게 된다.

 

실제로 응답이 200으로 온다.

 

이제 응답을 ResponseEntity로 보내보자.

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

의도대로 해당 Exception 발생시 500 을 return하도록 만들어 주었다.

또한 해당 Advice를 적용할 package, class 등을 별도로 지정할 수 도 있다.

@RestControllerAdvice(basePackageClasses = [ExceptionApiController::class]) //RestController에 대한 Advice
class GlobalControllerAdvice {

    @ExceptionHandler(value = [RuntimeException::class])
    fun exception(e: RuntimeException): String {
        return "Server Error"
    }

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

 

이와 같은 방법은 Global하게 처리하는 방법이다.

 

반면 Controller 내부에서만 예외 처리를 적용하고 싶다면??

 

메서드에 @ExceptionHandler적용하면 됨.

 

[API예외] @ExceptionHandler

1. HTML 화면 오류 & API 오류 웹 브라우저에 HTML 화면을 제공할 때는 오류가 발생하면 BasicErrorController 사용이 편함 이때는 단순히 5xx, 4xx 관련된 오류 화면을 보여주면 된다. BasicErrorController 는..

bsh-developer.tistory.com

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

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

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

 

 

 

GitHub


 

GitHub - bsh6463/KotlinSpring: GET

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

github.com

 

Comments