java - 在 Employee 的保存时间时使用 orElseThrow 方法抛出 ConstraintViolationException

标签 java spring rest spring-boot crud

我正在学习 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/

相关文章:

java - Hibernate 一对多映射

java - Tomcat 返回 404 状态

java - Spring 集成: Force Webservice Outbound Gateway to Use TLSv1

java - mybatis IllegalArgumentException : Mapped Statements collection does not contain value

java - 显示来自对 JSP 的 Web 服务调用的错误消息

java - 使用 Spring 保护用户帐户微服务

java - 以递归方式检查初学者(不是作业,是我学习的一部分)

Java 字符串匹配正则表达式

linux - 如何使用 Java 代码从远程计算机获取命令或 shell 脚本的响应

java - 如何在 Spring Boot 中为 RestTemplate 设置 PropertyNamingStrategy?