Loading...
Spring Framework Reference Documentation 7.0.2의 Error Responses의 한국어 번역본입니다.
아래의 경우에 피드백에서 신고해주신다면 반영하겠습니다.
감사합니다 :)
REST 서비스에 대해 error response의 body에 상세 정보를 포함해야 하는 요구 사항이 일반적입니다. Spring Framework는 "Problem Details for HTTP APIs" 명세인 RFC 9457를 지원합니다.
다음은 이 지원을 위한 주요 추상화입니다:
ProblemDetail — RFC 9457 problem detail에 대한 표현으로, 명세에서 정의한
표준 필드와 비표준 필드 모두를 위한 단순한 컨테이너입니다.
ErrorResponse — HTTP 상태, response 헤더, 그리고 RFC 9457 포맷의 body를 포함한
HTTP error response 상세 정보를 노출하기 위한 계약입니다. 이를 통해 exception이
HTTP response로 어떻게 매핑되는지에 대한 상세 정보를 캡슐화하고 노출할 수 있습니다.
모든 Spring MVC exception이 이것을 구현합니다.
ErrorResponseException — 다른 구현체들이 편리한 기본 클래스로 사용할 수 있는
기본적인 ErrorResponse 구현입니다.
ResponseEntityExceptionHandler — 모든 Spring MVC exception과
ErrorResponseException을 처리하고 body가 있는 error response를 렌더링하는
@ControllerAdvice를 위한 편리한 기본 클래스입니다.
RFC 9457 response를 렌더링하기 위해, 어떤 @ExceptionHandler 또는
어떤 @RequestMapping 메서드에서도 ProblemDetail 또는 ErrorResponse를
반환할 수 있습니다. 이는 다음과 같이 처리됩니다:
ProblemDetail의 status 프로퍼티가 HTTP 상태를 결정합니다.ProblemDetail의 instance 프로퍼티는 아직 설정되지 않은 경우 현재 URL 경로에서
설정됩니다.HttpMessageConverter는 ProblemDetail을
렌더링할 때 "application/json"보다 "application/problem+json"을 선호하며,
호환 가능한 미디어 타입을 찾지 못한 경우에도 이에 폴백합니다.Spring MVC exception과 모든 ErrorResponseException에 대해 RFC 9457 response를
활성화하려면, ResponseEntityExceptionHandler를 확장하고 이를 Spring 설정에서
@ControllerAdvice로 선언하면 됩니다. 이 핸들러는 모든
내장 웹 exception을 포함하는, 어떤 ErrorResponse exception도 처리하는
@ExceptionHandler 메서드를 가지고 있습니다. 더 많은 exception 처리 메서드를
추가할 수 있으며, protected 메서드를 사용하여 어떤 exception이든 ProblemDetail로
매핑할 수 있습니다.
WebMvcConfigurer를 사용하여 MVC 설정를 통해
ErrorResponse 인터셉터를 등록할 수 있습니다. 이를 사용하여 어떤 RFC 9457
response든 가로채고 특정 동작을 수행할 수 있습니다.
두 가지 방법 중 하나를 사용하여 비표준 필드로 RFC 9457 response를 확장할 수 있습니다.
첫째, ProblemDetail의 "properties" Map에 삽입하는 것입니다. Jackson
라이브러리를 사용할 때, Spring Framework는 이 "properties" Map이 언랩되어
response에서 top level JSON 프로퍼티로 렌더링되도록 보장하는
ProblemDetailJacksonMixin을 등록하며, 마찬가지로 역직렬화 중의 모든
알 수 없는 프로퍼티는 이 Map에 삽입됩니다.
또한 전용 비표준 프로퍼티를 추가하기 위해 ProblemDetail을 확장할 수도
있습니다. ProblemDetail의 복사 생성자는 서브클래스가 기존 ProblemDetail에서
쉽게 생성될 수 있도록 허용합니다. 이는 예를 들어 추가 비표준 필드를 가진 서브클래스로
exception의 ProblemDetail을 다시 생성하는 ResponseEntityExceptionHandler와 같은
@ControllerAdvice에서 중앙집중적으로 수행될 수 있습니다.
error response 상세 정보를 커스터마이즈하고 국제화하는 것은 일반적인 요구 사항입니다. 또한 구현 세부 사항이 드러나는 것을 피하기 위해 Spring MVC exception에 대한 problem detail을 커스터마이즈하는 것은 좋은 관행입니다. 이 섹션에서는 이를 위한 지원을 설명합니다.
ErrorResponse는 "type", "title", 그리고 "detail"에 대한 message code와, "detail"
필드에 대한 message code argument를 노출합니다.
ResponseEntityExceptionHandler는 이를
MessageSource를 통해 resolve하고, 해당하는
ProblemDetail 필드를 적절히 업데이트합니다.
message code에 대한 기본 전략은 다음과 같습니다:
problemDetail.type.[fully qualified exception class name]problemDetail.title.[fully qualified exception class name]problemDetail.[fully qualified exception class name][suffix]ErrorResponse는 일반적으로 기본 message code에 suffix를 추가하여, 하나 이상의
message code를 노출할 수 있습니다. 아래 표는 Spring MVC exception에 대한
message code와 argument를 나열합니다:
| Exception | Message Code | Message Code Arguments |
|---|---|---|
AsyncRequestTimeoutException | (default) | |
ConversionNotSupportedException | (default) | {0} 프로퍼티 이름, {1} 프로퍼티 값 |
HandlerMethodValidationException | (default) | {0} 모든 검증 오류 목록.<br>각 error에 대한 message code와 argument 또한 MessageSource를 통해 resolve됩니다. |
HttpMediaTypeNotAcceptableException | (default) | {0} 지원되는 미디어 타입 목록 |
HttpMediaTypeNotAcceptableException | (default) + ".parseError" | |
HttpMediaTypeNotSupportedException | (default) | {0} 지원되지 않는 미디어 타입, {1} 지원되는 미디어 타입 목록 |
HttpMediaTypeNotSupportedException | (default) + ".parseError" | |
HttpMessageNotReadableException | (default) | |
HttpMessageNotWritableException | (default) | |
HttpRequestMethodNotSupportedException | (default) | {0} 현재 HTTP 메서드, {1} 지원되는 HTTP 메서드 목록 |
MethodArgumentNotValidException | (default) | {0} 전역 오류 목록, {1} 필드 오류 목록.<br>각 error에 대한 message code와 argument 또한 MessageSource를 통해 resolve됩니다. |
MissingRequestHeaderException | (default) | {0} 헤더 이름 |
MissingServletRequestParameterException | (default) | {0} 요청 파라미터 이름 |
MissingMatrixVariableException | (default) | {0} 매트릭스 변수 이름 |
MissingPathVariableException | (default) | {0} 경로 변수 이름 |
MissingRequestCookieException | (default) | {0} 쿠키 이름 |
MissingServletRequestPartException | (default) | {0} 파트 이름 |
NoHandlerFoundException | (default) | |
NoResourceFoundException | (default) | {0} 리소스를 찾는 데 사용된 요청 경로(또는 그 일부) |
TypeMismatchException | (default) | {0} 프로퍼티 이름, {1} 프로퍼티 값, {2} 요구 타입의 단순 이름 |
UnsatisfiedServletRequestParameterException | (default) | {0} 파라미터 조건 목록 |
| 설명 | 내용 |
|---|---|
| Note | 다른 exception과 달리,<br>MethodArgumentValidException 및 HandlerMethodValidationException에 대한 message argument는<br>MessageSource resource bundle을 통해서도 커스터마이즈할 수 있는<br>MessageSourceResolvable error 목록을 기반으로 합니다.<br>자세한 내용은<br>Customizing Validation Errors를 참조하세요. |
클라이언트 애플리케이션은 WebClient를 사용할 때 WebClientResponseException을,
RestTemplate을 사용할 때 RestClientResponseException을 catch하고,
getResponseBodyAs 메서드를 사용하여 error response body를 ProblemDetail 또는
ProblemDetail의 서브클래스와 같은 임의의 대상 타입으로 디코딩할 수 있습니다.
API Versioning
Web Security