Skip to content

Commit bbfba8c

Browse files
committed
Refactoring Java 14 record to be serialized as JSON.
1 parent 3e270f4 commit bbfba8c

File tree

1 file changed

+39
-6
lines changed

1 file changed

+39
-6
lines changed
Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,48 @@
11
package com.siriusxi.ms.store.util.http;
22

3+
import com.fasterxml.jackson.annotation.JsonFormat;
4+
import com.fasterxml.jackson.annotation.JsonProperty;
5+
6+
import com.fasterxml.jackson.core.JsonProcessingException;
7+
import com.fasterxml.jackson.databind.ObjectMapper;
8+
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
9+
10+
import com.fasterxml.jackson.datatype.jsr310.ser.ZonedDateTimeSerializer;
311
import org.springframework.http.HttpStatus;
12+
413
import java.time.ZonedDateTime;
514

15+
/**
16+
* Record HttpErrorInfo which encapsulate all HTTP errors sent to client.
17+
*
18+
* Since it is a record and not normal POJO,
19+
* so it needs some customizations to be serialized to JSON.
20+
*
21+
* @author mohamed.taman
22+
* @version 0.4
23+
* @since v0.1
24+
* @see java.lang.Record
25+
*/
626
public record HttpErrorInfo(
7-
ZonedDateTime timestamp,
8-
String path,
9-
HttpStatus httpStatus,
10-
String message) {
27+
@JsonProperty("httpStatus") HttpStatus httpStatus,
28+
@JsonProperty("message") String message,
29+
@JsonProperty("path") String path,
30+
@JsonProperty("time")
31+
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
32+
@JsonSerialize(using = ZonedDateTimeSerializer.class)
33+
ZonedDateTime timestamp
34+
) {
35+
36+
public HttpErrorInfo( HttpStatus httpStatus, String path, String message) {
37+
this(httpStatus, message, path, ZonedDateTime.now());
38+
}
1139

12-
public HttpErrorInfo(HttpStatus httpStatus, String path, String message) {
13-
this(ZonedDateTime.now(), path, httpStatus, message);
40+
public static void main(String[] args) throws JsonProcessingException {
41+
HttpErrorInfo err = new HttpErrorInfo(HttpStatus.BAD_REQUEST,"/path", "Error man");
42+
HttpErrorInfo err1 = new HttpErrorInfo(HttpStatus.UNPROCESSABLE_ENTITY, "Error message man",
43+
"/path1234", ZonedDateTime.now());
44+
ObjectMapper mapper = new ObjectMapper();
45+
System.out.println(mapper.writeValueAsString(err));
46+
System.out.println(mapper.writeValueAsString(err1));
1447
}
1548
}

0 commit comments

Comments
 (0)