๋ก๊ทธ์ธ์ด ์๋ ์ํ์์ API ํธ์ถ ์ ๋ก๊ทธ์ธ ํํฐ๋ฅผ ํตํด ErrorResponse ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ค.
ํ์ง๋ง ํด๋น ์๋ต ๊ฐ์ฒด์์ LocalDateTime ์ง๋ ฌํ ์ค๋ฅ๊ฐ ๋ฐ์ํ์๋ค.
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.example.extendedscheduler.common.dto.ErrorResponse["timestamp"])
...
ObjectMapper ob = new ObjectMapper();
...
httpResponse.getWriter().write(ob.writeValueAsString(new ErrorResponse("๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค.
, HttpStatus.UNAUTHORIZED.value())));
...
์๋ต์ ErrorResponse ๊ฐ์ฒด๋ฅผ ๋ด๊ณ ์ถ์ด ObjectMapper ๋ฅผ ์์ฑํ๋ค.
//์๋ฌ ์๋ต๊ฐ์ฒด
@Getter
public class ErrorResponse {
private String message;
private int status;
private LocalDateTime timestamp;
public ErrorResponse(String message, int status) {
this.message = message;
this.status = status;
this.timestamp = LocalDateTime.now();
}
}
ErroResponse ์ timestamp ํ๋๋ LocalDateTime.now() ๋ฅผ ํตํด ์ด๊ธฐํ๋๋ค.
LocalDateTime ํ์
์ Jackson ๊ธฐ๋ณธ ์ค์ ์์ ์ง๋ ฌํ๊ฐ ๋ถ๊ฐ๋ฅํ์ฌ jackson-datatype-jsr310 ๋ชจ๋์ ๋ฐ๋์ ๋ฑ๋กํด์ค์ผ ํ๋ค.
๊ธฐ๋ณธ์ ์ผ๋ก Spring Boot๋ ObjectMapper์ ํด๋น ๋ชจ๋์ ํฌํจํ์ฌ ๊ด๋ฆฌํ๊ธฐ์ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ง ์์ง๋ง new ObjectMapper()๋ก ์ง์ ์์ฑํ ์ธ์คํด์ค์๋ ์คํ๋ง ์ค์ ์ด ๋ฐ์๋์ง ์์ ํด๋น ๋ชจ๋์ด ์๋์ผ๋ก ๋ฑ๋ก๋์ง ์๋๋ค.
...
ObjectMapper ob = new ObjectMapper();
ob.registerModule(new JavaTimeModule());
JavaTimeModule ์ ์ง์ ๋ฑ๋กํด์ฃผ๋ฉด LocalDateTime ์ง๋ ฌํ ์๋ฌ๋ ํด๊ฒฐ๋๋ค.
{
"message": "๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค.",
"status": 401,
"timestamp": [
2025,
5,
25,
23,
42,
35,
495226700
]
}
๋ฌธ์ ๋ ํด๊ฒฐ๋์ง๋ง timestamp๊ฐ ๋ด๊ฐ ์ํ๋ ISO-8601 ํฌ๋งท์ด ์๋ ๋ฐฐ์ด ํํ๋ก ์ถ๋ ฅ๋๋ค.
...
ObjectMapper ob = new ObjectMapper();
ob.registerModule(new JavaTimeModule());
ob.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
WRITE_DATES_AS_TIMESTAMPS๊ฐ ํ์ฑํ๋ผ ์์ผ๋ฉด ๋ฐฐ์ด ํํ๋ก JSON์ ํํ๋๋ค.
๋ฐ๋ผ์ ํด๋น ์ค์ ์ ๋๋ฉด ์ผ๋ฐ์ ์ธ ๋ ์ง ํฌ๋งท์ผ๋ก ๋์ค๊ฒ ํ ์ ์๋ค.
{
"message": "๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค.",
"status": 401,
"timestamp": "2025-05-26T00:55:06.7293507"
}
์ฒ์ ์ด ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ ๋ ErrorResponse๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ๋จ์ํ ์์ธ๋ง ๋ฐ์์ํค๋ ๋ฐฉ๋ฒ๋ ๊ณ ๋ คํ์ง๋ง
๊ณตํต์ ์ธ ์๋ต ํฌ๋งท์ ์ ์งํ๋ ๊ฒ์ด ๋ ๋์ ๋ฐฉํฅ์ด๋ผ๊ณ ํ๋จํ๋ค.
๊ฒฐ๊ตญ ๊ตฌ์กฐ๋ฅผ ํฌ๊ฒ ๋ณ๊ฒฝํ์ง ์๊ณ Jackson ์ค์ ๋ง์ผ๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์ด ๋คํ์ด์๋ค.