【发布时间】:2022-01-10 03:40:06
【问题描述】:
我在 Spring/JPA 中有一个简单的问题。据说,我有这种格式的请求:
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;
}
}
或作为这种json格式
{
"desc": "String",
"id": 0,
"amount": 0
}
这是控制器
controller/BillController.java
@RequestMapping(method = RequestMethod.POST)
public void create(@RequestBody BillDto billDto) {
billService.create(billDto); // some service to execute
}
但是,当我不小心以错误的格式请求时,生成的 SQL 将不会执行,因此它返回 500 代码。例如,
{
"desc": "String",
"id": 0
}
如何在最短的代码行中处理此错误?在将它传递给服务之前,如何验证 json 请求以匹配模型/dto?
【问题讨论】:
-
句柄是什么意思?即使提交的请求(JSON)不完整,也要避免得到 500 代码?
标签: java json spring spring-boot