【发布时间】:2020-02-12 12:02:33
【问题描述】:
我正在学习 Spring Boot,如果在保存时任何员工字段为空,我想在保存时显示错误消息。但是orElseThrow 方法显示错误。我怎样才能节省时间?
@ApiOperation(value = "Add an employee")
@PostMapping("/createemployee")
Employee createOrSaveEmployee(
@ApiParam(value = "Employee object store in database table", required = true)
@Valid
@RequestBody Employee newEmployee)
throws BadRequestExceptionHandler, ConstraintViolationException {
/*in below line orElseThrow method shows error
that create new method named as orElseThrow in Employee Pojo. */
return employeeRepository.save(newEmployee)
.orElseThrow(() -> new ConstraintViolationException("Required parameters can not be empty."));
}
【问题讨论】:
-
存储库
save方法不返回Optional,您不能使用orElseThrow。我不知道您使用的是哪种数据库,但是如果在数据库级别需要某些字段,那么如果您尝试插入与预期不符的行,ORM 框架应该会引发异常。只要做一些调查就知道在这种情况下抛出了什么样的异常并处理它 -
“...创建新方法的错误...”您是否会将其改写为“...orElseThrow 方法显示错误:在 Employee Pojo 中创建名为 orElseThrow 的新方法”?
标签: java spring rest spring-boot crud