[SpringBoot] 예외처리 핸들링 (3) - ExceptionHandler

해니·2024년 9월 30일
0

SpringBoot

목록 보기
20/24
post-thumbnail

전역으로 예외처리

Exeption을 공통으로 처리하는 방법은 크게 두 가지가 있다.

  • AbstractHandlerExceptionResolver 를 상속받아 ExceptionResolver를 구현
  • @ControllerAdvice, @ExceptionHandler 어노테이션을 사용하여 ExceptionHandler를 구현

ExceptionResolver 구현 방법은 지난 포스팅에 정리했고, 이번엔 ExceptionHandler 구현 방법에 대해 기록합니다. 🤓



@ControllerAdvice와 @RestControllerAdvice

  • 해당 어노테이션이 붙은 컨트롤러에서는 발생하는 예외를 AOP(관점지향 프로그래밍)를 적용해 예외를 전역적으로 처리할 수 있다.
    • @ExceptionHandler, @InitBinder, @ModelAttribute가 적용된 메소드에 AOP를 적용하기 위해 고안되었다.
    • @Component가 포함되어 있기 때문에, 빈으로 관리된다.
  • @RestControllerAdvice 어노테이션은 @ResponseBody을 포함하기 때문에, 응답값을 JSON 형태로 내려준다.



@ExceptionHandler

  • 해당 어노테이션을 메소드에 선언해 예외 처리를 하려는 클래스를 지정하면, 예외 발생 시 정의된 로직에 의해 처리하게 된다.

ExceptionHandler 구현 예시

package com.money.moa.common.exception.handler

import com.money.moa.common.dto.ResponseDto
import com.money.moa.common.exception.CommonException
import org.springframework.core.Ordered
import org.springframework.core.annotation.Order
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice

@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
class CommonExceptionHandler {

    @ExceptionHandler(CommonException::class)
    fun handleBizException(ex: CommonException): ResponseEntity<ResponseDto<*>> {
        val response = ResponseDto(
                code = ex.code ?: HttpStatus.INTERNAL_SERVER_ERROR.value(),
                message = ex.message,
                error = ex.message,
                response = null // 일단 null
        )
        return ResponseEntity.status(response.code).body(response)
    }
}




출처

[Spring] 전역 예외 처리를 위한 @ControllerAdvice와 @RestControllerAdvice
@RestControllerAdvice를 이용한 예외처리

profile
💻 ⚾️ 🐻

0개의 댓글