Spring - 无法捕获 ConstraintViolationException

use*_*ser 4 spring spring-data spring-data-jpa

我的服务中有一个方法:

@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");
        }
    }
Run Code Online (Sandbox Code Playgroud)

用户类:

@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;
Run Code Online (Sandbox Code Playgroud)

问题是当我发送 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"
}
Run Code Online (Sandbox Code Playgroud)

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

Sta*_*avL 5

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

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

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