|
1 | 1 | package com.siriusxi.ms.store.util.http;
|
2 | 2 |
|
| 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; |
3 | 11 | import org.springframework.http.HttpStatus;
|
| 12 | + |
4 | 13 | import java.time.ZonedDateTime;
|
5 | 14 |
|
| 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 | + */ |
6 | 26 | 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 | + } |
11 | 39 |
|
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)); |
14 | 47 | }
|
15 | 48 | }
|
0 commit comments