I have been stuck on this issue for some time. I am using LocalDate
to accept date inputs from user via a REST endpoint. I want to validate this date to check if it's null
, empty
string or invalid
date such as Feb 30
. I have managed to get it to work for valid date values but in case of invalid input, it's throwing 400 Bad Request
in response which is coming from internal classes of Java so I don't have any control over it. If you could please let me know if I am missing something or doing it wrong, I will really appreciate it.
This is called method in my controller - annotated with @Valid:
@RequestMapping(method = RequestMethod.PUT, value="/add")
public ResponseEntity<PSResponse> add(@Valid @RequestBody PSRequest request) throws Exception {
setServiceID(SERVICE_HANDLER_ID);
request.setRequestType("add");
PSResponse response = (PSResponse) invokeInternal(request);
}
This is class for my request object
public class PSRequest {
@NotNull(message = "fromDate cannot be null")
protected LocalDate fromDate;
@NotNull(message = "toDate cannot be null")
protected LocalDate toDate;}
Valid JSON input
"fromDate":2020-10-16"
"toDate":"2021-10-16"
Invalid JSON input date formats
"fromDate":null,
"toDate":"2021-02-30"
Thanks!
CodePudding user response:
There is nothing wrong with what you are doing and it is normal to get a 400 bad request
.
Why? Because you are working with Rest Endpoint which is based on Http
protocol
A Bad request
means that your Http
request is not correct due to many reason such as : invalid parameters. The best practice is to send a clear message to the user explaining what happened after the request he send to the server. To do that you can use RestControllerAdvice to intercept all your exceptions and map it to Http
status codes.
Check this post for more details.
CodePudding user response:
In order to suppress the build-in validations, you can recieve String
from the frontend, and only then do your code: LocalDate.parse(fromDate)
, catch the DateTimeParseException
and handle it as you wish.
Another option is to remove the @Valid
By the way, what's wrong with @Valid
? Don't you want to have 400 in return anyway ?! or you'd like to control the body message with the 400 ?