我正在学习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."));
    }

最佳答案

Optional退货可以使用orElseThrow()处理。无需尝试这种方式,您几乎可以以这种方式涵盖相同的异常,也可以使用您自己的引发异常的方式。

try{
  employeeRepository.save(newEmployee);
}catch(ConstraintViolationException e){
  throw new OwnDefinedException("Required parameters can not be empty.");
}

07-26 06:05