2 min read

ResponseEntity 대신 ProblemDetail 사용해보기

API 오류 응답 바디의 표준 형식(RFC 9457)을 Spring이 클래스로 만들어둔 것이다 (Spring 6부터). Content-Type은 application/problem+json으로 나간다.

json
{
  "type": "about:blank",
  "title": "Not Found",
  "status": 404,
  "detail": "Post not found: abc",
  "instance": "/api/posts/abc"
}
필드뜻
type오류 종류를 나타내는 URI. 정하지 않으면 about:blank
title상태 코드의 짧은 설명
statusHTTP 상태 코드
detail이번 오류의 구체적인 설명
instance오류가 난 요청 경로

ResponseEntity와는 하는 일이 다르다. 둘 중 하나를 고르는 관계가 아니다.

  • ResponseEntity: HTTP 응답 전체(상태 코드, 헤더, 바디)를 감싸는 포장지
  • ProblemDetail: 그 안에 들어갈 바디의 형식

그래서 ResponseEntity.status(404).header(...).body(problemDetail)처럼 같이 쓸 수도 있다. ProblemDetail만 반환하면 Spring이 안의 status를 보고 HTTP 상태 코드를 알아서 정해주므로, 헤더를 붙일 일이 없으면 감쌀 필요가 없다.

이걸 고른 이유

  1. 표준이라 오류 바디 클래스(ErrorResponse 같은)를 직접 설계하지 않아도 된다
  2. spring.mvc.problemdetails.enabled: true를 켜면 Spring 자체 오류(잘못된 요청 400, 없는 경로 404 등)도 같은 형식으로 나간다. 직접 만든 오류와 모양이 달라지지 않는다
  3. 필드가 더 필요하면 problem.setProperty("code", "POST_NOT_FOUND")처럼 붙이면 된다
공유

댓글