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?
Catch the exception above. Out of the method annotated with @Transactional
.
In you case you intercept the exception and swallow but DB state is still incorrect. So on attempt to commit after the exit of annotated method it fails.
Or add an ExceptionHandler to catch this exception and return correct response.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With