Issue
I have a simple problem in Spring/JPA. Supposedly, I have this format of request:
model/BillDto.java
public class BillDto {
private String desc;
private Long id;
private Integer amount;
public BillDto(String desc, long id, int amount) {
this.desc = desc;
this.id = id;
this.amount = amount;
}
}
or as this json format
{
"desc": "String",
"id": 0,
"amount": 0
}
And this is the controller
controller/BillController.java
@RequestMapping(method = RequestMethod.POST)
public void create(@RequestBody BillDto billDto) {
billService.create(billDto); // some service to execute
}
However when I accidentally request with wrong format, the generated SQL won't execute, hence it returns 500 code. For example,
{
"desc": "String",
"id": 0
}
How do I handle this error in shortest lines of codes? How do I validate the json request to match the model/dto before passing it to service?
Solution
You can use @Valid
annotation to the BillDto parameter annotated with @RequestBody. This will tell Spring to process validation before making an actual method call. In case validation fails, Spring will throw a MethodArgument NotValidException
which, by default, will return a 400 (Bad Request) response.
@RequestMapping(method = RequestMethod.POST)
public void create(@Valid @RequestBody BillDto billDto) {
billService.create(billDto); // some service to execute
}
In POST or PUT requests, when we pass JSON payload, Spring automatically converts it into a Java object and now it can validate the resulting object.
Answered By - user10260739
Answer Checked By - Gilberto Lyons (JavaFixing Admin)