2021-06-27

Spring custom error response: timeStamp vs timestamp

I made a custom error message

private final ??? timestamp;
private final HttpStatus status;
private final String message;
private List<ValidationError> errors;

The thing is that no matter the timestamp field type it seems like somewhere this field gets overwritten.

For example, say that timestamp field is a String. By posting a http request i get an error in this format

 "status": "CONFLICT",
 "message": "UserNameTakenException",
 "errors": null,
 "timeStamp": "this is a date"

Why timestamp becomes timeStamp? Not only that, but having

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private final LocalDateTime timestamp;

produces errors with 2 timestamps!

 "timestamp": "26-06-2021 10:22:36",
 "status": "CONFLICT",
 "message": "UserNameTakenException",
 "errors": null,
 "timeStamp": "2021-06-26T22:22:36.283862"

What the heck is happening here? Im using an ControllerAdvice to catch the exception and then produce the response

  @ExceptionHandler(UserNameTakenException.class)
  @ResponseStatus(HttpStatus.CONFLICT)
  public ResponseEntity<Object> handleUserNameTakenException(UserNameTakenException ex, WebRequest request) {
    ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT, ex.getMessage());  
    return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse);
}

UPDATE: Ok, so i tried to change the custom error's getter for timestamp

public LocalDateTime getTimeStamp() {
    return this.timestamp;
}

The getter is being used not only to retrieve the value (which is private) but also to name the json reponse field. So, hanging getTimeStamp to getTimestamp changes the json's timestamp name. I just removed the getter.



from Recent Questions - Stack Overflow https://ift.tt/3xOahUm
https://ift.tt/eA8V8J

No comments:

Post a Comment