bestsource

Spring Boot 사용자 지정 http 오류 응답?

bestsource 2023. 7. 18. 21:51
반응형

Spring Boot 사용자 지정 http 오류 응답?

Spring Boot 웹 응용 프로그램에서 예외가 발생한 경우 응답 상태 코드와 응답 본문의 데이터를 사용자 지정하려면 어떻게 해야 합니까?

내부 상태가 좋지 않아 예상치 못한 일이 발생하면 사용자 지정 예외를 던지는 웹 앱을 만들었습니다.따라서 오류를 트리거한 요청의 응답 본문은 다음과 같습니다.

HTTP/1.1 500 Internal Server Error
{
    "timestamp": 1412685688268,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "com.example.CustomException",
    "message": null,
    "path": "/example"
}

이제 상태 코드를 변경하고 응답 본문의 필드를 설정하려고 합니다.제 머리 속에 떠오른 한 가지 해결책은 다음과 같습니다.

@ControllerAdvice
class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    ErrorMessage handleBadCredentials(CustomException e) {
        return new ErrorMessage("Bad things happened");
    }
}

@XmlRootElement
public class ErrorMessage(
    private String error;

    public ErrorMessage() {
    }

    public ErrorMessage(String error) {
        this.error = error;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }
)

그러나, 그것은 (의심되는 것처럼) 완전히 다른 반응을 만들었습니다.

HTTP/1.1 400 Bad Request
{
    "error": "Bad things happened"
}

@zeroflagL이 언급했듯이, 스프링 부트는 다음에서 "표준" 오류 응답 본체를 제작합니다.org.springframework.boot.autoconfigure.web.DefaultErrorAttributes귀사의 요구 사항과 유사하게, 이 모든 것을 활용하되, 일부 예외 사항에 의해 제공된 "유형" 필드를 하나 더 추가하고 싶었습니다.

저는 그것을 구현함으로써 했습니다.Component저 아류의DefaultErrorAttributesSpring Boot은 자동으로 그것을 집어서 기본값이 아닌 내 것을 사용했습니다.

@Component
public class ExtendedErrorAttributes extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, 
                                                  boolean includeStackTrace) {
        final Map<String, Object> errorAttributes = 
            super.getErrorAttributes(requestAttributes, 
                                     includeStackTrace);

        final Throwable error = super.getError(requestAttributes);
        if (error instanceof TypeProvider) {
            final TypeProvider typeProvider = (TypeProvider) error;
            errorAttributes.put("type", typeProvider.getTypeIdentifier());
        }

        return errorAttributes;
    }
}

그것으로, 저는 증강된 JSON 대응체를 얻습니다.

{
  "timestamp": 1488058582764,
  "status": 429,
  "error": "Too Many Requests",
  "exception": "com.example.ExternalRateLimitException",
  "message": "DAILY_LIMIT: too many requests",
  "path": "/api/lookup",
  "type": "DAILY_LIMIT"
}

HttpServletResponse를 사용하여 http 응답 상태 코드를 변경할 수 있습니다.sendError(int) 메서드(예:

@ExceptionHandler
void handleIllegalArgumentException(IllegalArgumentException e, HttpServletResponse response) throws IOException {
    response.sendError(HttpStatus.BAD_REQUEST.value());
}

또는 에서 예외 유형을 선언할 수 있습니다.@ExceptionHandler동일한 응답 상태를 생성하기 위한 두 개 이상의 예외가 있는 경우 주석:

@ExceptionHandler({IllegalArgumentException.class, NullPointerException.class})
void handleBadRequests(HttpServletResponse response) throws IOException {
    response.sendError(HttpStatus.BAD_REQUEST.value());
}

더 많은 정보는 제 블로그 게시물에서 찾을 수 있습니다.

언급URL : https://stackoverflow.com/questions/26236811/spring-boot-customize-http-error-response

반응형