ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring Boot : ProblemDetailsExceptionHandler
    Spring Boot 2024. 4. 10. 18:55

    ProblemDetail

    ProblemDetail은 Spring Framework 6.0에 추가된 REST API의 에러 응답 표준이다.
    RFC 7807에 정의되어 있다.

    아래는 간단히 Spring Boot의 기본 에러 응답을 ProblemDetail로 설정하는 방법을 설명한다.

    ProblemDetailsExceptionHandler

    에러 응답 예시

    아래는 Spring Boot의 기본 에러 응답을 ProblemDetail로 설정했을 때의 에러 응답 body이다.

    {
        "type": "about:blank",
        "title": "Method Not Allowed",
        "status": 405,
        "detail": "Method 'POST' is not supported.",
        "instance": "/"
    }

    Spring Boot 설정

    아래 설정을 추가하면 ProblemDetailsExceptionHandler가 자동 구성된다.
    이를 통해 Spring Framework에서 제공하는 웹 예외들은 자동으로 ProblemDetail 형식의 response body로 에러 응답을 한다.

    spring.mvc.problemdetails.enabled=true

    자동 구성

    위의 설정이 되어있으면 아래 클래스에서 ProblemDetailsExceptionHandler가 자동 구성된다.

    package org.springframework.boot.autoconfigure.web.servlet;
    
    public class WebMvcAutoConfiguration {
    
        @Configuration(proxyBeanMethods = false)
        @ConditionalOnProperty(prefix = "spring.mvc.problemdetails", name = "enabled", havingValue = "true")
        static class ProblemDetailsErrorHandlingConfiguration {
    
            @Bean
            @ConditionalOnMissingBean(ResponseEntityExceptionHandler.class)
            @Order(0)
            ProblemDetailsExceptionHandler problemDetailsExceptionHandler() {
                return new ProblemDetailsExceptionHandler();
            }
    
        }
    }

    자동 구성되는 ProblemDetailsExceptionHandler

    ResponseEntityExceptionHandler를 확장한 구현 클래스일 뿐이다.

    package org.springframework.boot.autoconfigure.web.servlet;
    
    @ControllerAdvice
    class ProblemDetailsExceptionHandler extends ResponseEntityExceptionHandler {
    }
Designed by Tistory.