我正在学习 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."));
}
最佳答案
可选
返回可以用orElseThrow()
处理。您可以通过这种方式以及您自己的抛出异常的方式几乎覆盖相同的异常,而不是尝试这种方式。
try{
employeeRepository.save(newEmployee);
}catch(ConstraintViolationException e){
throw new OwnDefinedException("Required parameters can not be empty.");
}
关于java - 在 Employee 的保存时间时使用 orElseThrow 方法抛出 ConstraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60187902/