prosource

Spring Boot Rest 컨트롤러에서 기본 JSON 오류 응답 수정

probook 2023. 4. 3. 21:36
반응형

Spring Boot Rest 컨트롤러에서 기본 JSON 오류 응답 수정

현재 스프링 부트 오류 응답에는 다음과 같은 표준 내용이 포함되어 있습니다.

{
   "timestamp" : 1426615606,
   "exception" : "org.springframework.web.bind.MissingServletRequestParameterException",
   "status" : 400,
   "error" : "Bad Request",
   "path" : "/welcome",
   "message" : "Required String parameter 'name' is not present"
}

응답의 '예외' 속성을 제거할 방법을 찾고 있습니다.이것을 달성할 수 있는 방법이 있나요?

에러 처리의 메뉴얼에 기재되어 있듯이, 독자적인 빈을 제공하면,ErrorAttributes콘텐츠를 관리할 수 있습니다.

그렇게 하는 쉬운 방법은 서브클래스를 사용하는 것입니다.DefaultErrorAttributes. 예:

@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
            // Customize the default entries in errorAttributes to suit your needs
            return errorAttributes;
        }

   };
}

예외가 발생했을 때 json에 빈 메시지텍스트가 있는 경우 스프링부트 2.3.0에서 변경된 동작이 발생할 수 있습니다.이 경우 변경만 하면 됩니다.server.error.include-message의 재산.always.

다음 답변은 Andy Wilkinson의 답변(클래스 사용)에서 완전히 파생되었습니다.
- 다음을 포함합니다.web.servlet베이스 클래스
- 스프링 부트 2.2.4.풀어주다

ExceptionHandlerConfig.java

package com.example.sample.core.exception;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.WebRequest;

@Configuration
public class ExceptionHandlerConfig {

    //private static final String DEFAULT_KEY_TIMESTAMP = "timestamp";
    private static final String DEFAULT_KEY_STATUS = "status";
    private static final String DEFAULT_KEY_ERROR = "error";
    private static final String DEFAULT_KEY_ERRORS = "errors";
    private static final String DEFAULT_KEY_MESSAGE = "message";
    //private static final String DEFAULT_KEY_PATH = "path";

    public static final String KEY_STATUS = "status";
    public static final String KEY_ERROR = "error";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_TIMESTAMP = "timestamp";
    public static final String KEY_ERRORS = "errors";

    //

    @Bean
    public ErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes() {

            @Override
            public Map<String ,Object> getErrorAttributes(
                WebRequest webRequest
                ,boolean includeStackTrace
            ) {
                Map<String ,Object> defaultMap
                    = super.getErrorAttributes( webRequest ,includeStackTrace );

                Map<String ,Object> errorAttributes = new LinkedHashMap<>();
                // Customize.
                // For eg: Only add the keys you want.
                errorAttributes.put( KEY_STATUS, defaultMap.get( DEFAULT_KEY_STATUS ) );                    
                errorAttributes.put( KEY_MESSAGE ,defaultMap.get( DEFAULT_KEY_MESSAGE ) );

                return errorAttributes;
            }
        };
    }
}

언급URL : https://stackoverflow.com/questions/29106637/modify-default-json-error-response-from-spring-boot-rest-controller

반응형