I'm using @RepositoryRestResource to create my REST API, that avoids having to manually write the code as in @RestController, and gives me a nice HATEOAS response. However now the validations I added to my entity don't work, or rather I get the 500 response code instead of 400.
I tried using @ControllerAdvice + @ExceptionHandler to capture the ConstraintViolationException, however it seems that it's being captured before and what's thrown is a TransactionSystemException.
Validating the data is something pretty basic, and yet for some reason after much googling I haven't found a solution.
edit: To show the code:
@ControllerAdvice
public class ConstraintViolationExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ ConstraintViolationException.class })
public ResponseEntity<Object> handleConstraintViolationException(
Exception ex, WebRequest request) {
return new ResponseEntity<Object>("test 123", HttpStatus.BAD_REQUEST);
}
}
I still get:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction] with root cause javax.validation.ConstraintViolationException
So it seems the ConstraintViolationException is being captured earlier by Spring Data REST and a TransactionSystemException is thrown. If I change the code to capture this exception like:
@ControllerAdvice
public class ConstraintViolationExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ TransactionSystemException .class })
public ResponseEntity<Object> handleConstraintViolationException(
Exception ex, WebRequest request) {
return new ResponseEntity<Object>("test 123", HttpStatus.BAD_REQUEST);
}
}
Then it works, but this is not the exception I should be capturing.