gpt4 book ai didi

Spring - 无法捕获 ConstraintViolationException

转载 作者:行者123 更新时间:2023-12-05 00:50:55 25 4
gpt4 key购买 nike

我的服务中有一个方法:

@Transactional
public MyResponse create(UserCredentials cred) {
User user = new User(cred);
try {
final User created = userRepository.save(user);
return new MyResponse(user, "Created");
} catch (TransactionSystemException e) {
return new MyResponse(null, "Cannot create");
} catch (ConstraintViolationException e) {
return new MyResponse(null, "Cannot create");
}
}

用户类:
@Entity
@Table(name = "users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(
name = "id",
updatable = false,
nullable = false
)
private Long id;

@NotBlank
@Column(
nullable = false,
unique = true
)
private String username;

@NotBlank
@Column(
nullable = false,
unique = true
)
private String email;

@NotBlank
@Column(nullable = false)
private String password;

问题是当我发送 JSON 空用户名或空电子邮件时。当我调试应用程序时,我得到 ConstraintViolationExcpetion,但在 JSON 响应中我得到:
{
"timestamp": 1500026388864,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.transaction.TransactionSystemException",
"message": "Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly",
"path": "/register"
}

调试器在 catch(ConstraintViolationException e) 处停止,但最后我得到 SystemTransactionException,为什么?

最佳答案

捕获上面的异常。用@Transactional注解出的方法.

在您的情况下,您拦截异常并吞下,但数据库状态仍然不正确。因此,在带注释的方法退出后尝试提交时,它会失败。

或者添加一个 ExceptionHandler 来捕获这个异常并返回正确的响应。

关于Spring - 无法捕获 ConstraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45100406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com