반응형
05-02 12:14
Today
Total
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
관리 메뉴

개발하는 고라니

[Spring Boot] API Error message가 나오지 않을 때 본문

Framework/Spring Boot

[Spring Boot] API Error message가 나오지 않을 때

조용한고라니 2023. 2. 27. 17:59
반응형

specification]

spring boot - 2.6.3

서론

API를 만들면 종종 Exception이 발생하기 마련이다.

Client에서 요청을 했는데, 예외가 발생했을 때 구체적이고 명시적으로 어떤 에러, 무엇 때문에 발생했는지를 "message"에 담아서 보낸다.

fun validateMoney(money: BigDecimal) {
  if (money < BigDecimal(0)) {
    throw MinusMoneyException("금액이 음수입니다. money : $money")
  }
}

하지만, 그간 무심코 넘어갔지만 에러 메세지를 확인해보려니 다음과 같이 발생한 적이 있을 것이다.

{
    "timestamp": "2023-02-27T08:43:33.081+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "path": "/api/v1/samples/error"
}

난 분명히 메세지를 전달했는데...?

본론

다음과 같이 Error를 발생하는 API가 있다고 하자.

@RestController
class SampleController {

    @GetMapping("/api/v1/samples/error")
    fun throwException(): ResponseEntity<*> {

        throw RuntimeException("sample 예외가 발생합니다.")
    }
}

 

이를 postman에서 호출했고, 나는 "sample 예외가 발생합니다" 라는 메세지를 받고싶으나, 다음과 같이 발생한다.

 

내 메세지는 어디갔을까.. 답은 baeldung에서 찾을 수 있었다.

Starting from the 2.3 version, Spring Boot doesn't include an error message on the default error page. 
The reason is to reduce the risk of leaking information to a client

spring boot 2.3 버전 부터는 클라이언트에 정보가 누수될까봐, 기본 에러페이지에 에러메세지를 담지 않는다고 한다.

결론

해결법은 간단했다. 

YAML or properties 파일에 설정하나만 넣어주면 된다.

# application.yml
server:
  error:
    include-message: always
    
# application.properties
server.error.include-message=always

다시 위 경로로 호출해보니, 기대하던 결과가 반환되었다.

{
    "timestamp": "2023-02-27T08:56:40.461+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "message": "sample 예외가 발생합니다.",
    "path": "/api/v1/samples/error"
}

 

# 코드

 

[add-error-message] by poby-kr · Pull Request #4 · rhacnddl/monorepo

[add-error-message] 에러 API 생성 error message 노출여부 설정

github.com

 

# Reference

https://www.baeldung.com/spring-response-status-exception

반응형
Comments