표준화 예외 포멧

에러 응답을 모두 제각각 만들지 말고, 공통된 표준 포맷으로 내려주자는 취지로, RFC 9457 Problem Details for HTTP APIs를 참고할 수 있다.

해당 문서를 기반으로 Spring Framework6 부터는 대표 필드 5가지를 표현하는 ProblemDetail 이라는 클래스가 추가되었다. 해당 예외 응답 포멧으로 공통화하는 방법도 인지하고 넘어가자.

// 위치 
org.springframework.http.ProblemDetail;


// 대표 필드
private URI type = BLANK_TYPE;  
  
@Nullable  
private String title;  
  
private int status;  
  
@Nullable  
private String detail;  
  
@Nullable  
private URI instance;  
  
@Nullable  
private Map<String, Object> properties;

예시

1. Type: 에러의 종류를 식별하는 URI

"type": "https://example.com/errors/invalid-input"

2. Title: 사람이 읽기 쉬운 짧은 에러 요약

"title": "Invalid Request"

3. status: HTTP 상태 코드

"status": 400

4. detail: 현재 발생한 문제에 대한 구체적인 설명

"detail": "Your current balance is 30, but that costs 50."

5. instance: 현재 발생한 에러 사례의 식별자

"instance": "/errors/abc123"

전체 포멧 예시

{
  "type": "...",
  "title": "...",
  "status": 400,
  "detail": "...",
  "errors": [
    {
      "field": "email",
      "reason": "must not be blank"
    }
  ]
}