Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Cannot catch ConstraintViolationException

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?

like image 402
user Avatar asked Jan 30 '23 00:01

user


1 Answers

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.

like image 179
StanislavL Avatar answered Feb 05 '23 14:02

StanislavL