繁体   English   中英

如何在 Java 中使用自定义值抛出自定义异常?

[英]How to throw custom exception with custom values in Java?

大家好,我在 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 条件? 非常感谢任何答案。 提前致谢。

让我们创建一个自定义的 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。 extra 方法与我们通常为处理所有异常而创建的方法非常相似。 事实上,您可以轻松地为所有异常复制粘贴此方法。 您所要做的就是将 Exception 类更改为您的异常并更改 HttpStatus。 .

@ExceptionHandler(ResourceAlreadyExistsException.class)
public final ResponseEntity<ExceptionResponse> handleResourceAlreadyExistsException(
    ResourceAlreadyExistsException ex, WebRequest req) {
    ExceptionResponse exceptionResponse = new ExceptionResponse(
        new Date(),
        ex.getMessage(),
        req.getDescription(false)
    );
    return new ResponseEntity<>(exceptionResponse, HttpStatus.UNPROCESSABLE_ENTITY);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM