Spring - Cannot catch ConstraintViolationException

Viewed 9837

I have a method in my service:

@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");
        }
    }

User class:

@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;

And the problem is when I send in JSON empty username or empty email. When I debug application I get ConstraintViolationExcpetion, but in JSON response I get:

{
    "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"
}

Debugger is stopping at catch(ConstraintViolationException e), but finally I get SystemTransactionException, why?

2 Answers
Related