【问题标题】:How to throw custom exception with custom values in Java?如何在 Java 中使用自定义值引发自定义异常?
【发布时间】:2020-11-20 10:42:37
【问题描述】:

大家好,我正在使用带有 MySQL 的 Spring Boot。我尝试查找信息时出现以下错误,

javax.persistence.NonUniqueResultException: 查询没有返回一个 唯一结果:2

在我的 Repository 类中,我有以下代码,

可选的 findByIdOrEmail(Integer id, String email);

我认为错误是因为 findByIdOrEmail 获取多条记录,因为 OR 运算符。

所以我使用List 来获取值,下面是我的代码,我的目标是抛出一个异常,专门显示每个重复值。

List<User> userList = userRepo.findByIdOrEmail(user.getId(), user.getEmail());

// There will be maximum of 2 records fetched by id and email and I didn't 
check if each result is the users record
if (!userList.isEmpty() && userList.size() > 1)
    throw new CustomException("Duplicate Record Found" +
            " id: " + user.getId() + " and email: " + user.getEmail());
else if (!userList.isEmpty())
    throw new CustomException("Duplicate Record Found" +
            (userList.get(0).getId().equals(user.getId()) ? "id: " + user.getId() : "email: " + user.getEmail()));

所以我想知道这种方法是最好的还是有其他最佳做法?因为用户应该能够更新他/她的记录,但可以检查与现有其他记录的重复项。而且由于它有时会给出一个值列表,所以我必须循环检查它们。那件事是我在上面的代码中没有做过。那么是否有另一种最好的方法或简单的方法来做到这一点而无需循环和多个 if 条件?非常感谢任何答案。提前致谢。

【问题讨论】:

  • 你好,看看有没有用dzone.com/articles/…
  • 是的,我已经做到了。我用@ContollerAdvice。但是我只需要上面代码sn-p的解决方案?
  • 你考虑过 Java 8 流 apis..filter.. 等吗?
  • 除此之外还有什么办法吗?

标签: java spring-boot exception spring-data-jpa operators


【解决方案1】:

让我们创建一个自定义 ResourceAlreadyExistsException 类。它将扩展 RuntimeException 类,您可以根据需要向其添加任意数量的参数。我一直保持这样简洁。

public class ResourceAlreadyExistsException extends RuntimeException {

    public ResourceAlreadyExistsException(String property, String value) {
        super(String.format(
            "Resource with property %s and value %s already exists." +
            "Make sure to insert a unique value for %s",
            property, value, property));
    }
}

每当我需要检查唯一资源时,我都可以告诉用户哪个特定属性具有导致错误的值。此外,我通知用户必须采取什么措施来避免错误。

说,我选择对我的 ResourceAlreadyExistsException 使用错误 ***。不过,我需要将此错误消息连接到 ExceptionResponseHandler。额外的方法与我们通常创建的用于处理所有异常的方法非常相似。事实上,您可以轻松地复制粘贴此方法来处理您拥有的所有异常。您所要做的就是将 Exception 类更改为您的异常并更改 HttpStatus..

@ExceptionHandler(ResourceAlreadyExistsException.class)
public final ResponseEntity handleResourceAlreadyExistsException(
    ResourceAlreadyExistsException ex, WebRequest req) {
    异常响应异常响应 = 新异常响应(
        新日期(),
        例如getMessage(),
        req.getDescription(false)
    );
    返回新的 ResponseEntity(exceptionResponse, HttpStatus.UNPROCESSABLE_ENTITY);

【讨论】:

  • 非常感谢您的回答和您的宝贵时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 1970-01-01
  • 2012-07-23
相关资源
最近更新 更多