Reputation: 57
I am using spring data jpa to save entities in the database. I am getting TransientPropertyValueException which is because I am trying to save a product which has an associated brand which is not saved. I want to catch TransientPropertyValueException which seems to be impossible. I know I can solve this problem by using CascadeType. But I do not want to use that. Instead I want to catch the exception and rethrow CustomException with a message. How can I catch this exception. Any comment is appreciated. Thanks in advance.
I tried this as well
if(exception.getCause() instanceof TransientPropertyValueException)
but this does not work.
Entity Class
@Entity
@Table(name = "Product")
public class Product implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PRODUCT_SEQ")
@SequenceGenerator(name="PRODUCT_SEQ", sequenceName = "PRODUCT_SEQ", allocationSize=1)
@Column(name = "PRODUCT_ID", nullable = false)
private long productId;
@OneToOne
@JoinColumn(name = "BRAND_ID", nullable = false)
private Brand brandId;
This is how I intend to catch it.
catch(Exception e) {
if (exception.getCause() instanceof ConstraintViolationException)
throw new CustomException("...");
// catch TransientPropertyValueException
if (exception.getCause() instanceof TransientPropertyValueException)
throw new CustomException("...");
}
Upvotes: 0
Views: 212
Reputation: 3572
You could try:
import org.apache.commons.lang3.exception.ExceptionUtils;
...
int index = ExceptionUtils.indexOfThrowable(exception, TransientPropertyValueException.class);
if (index > 0) {
//here we are
}
...
One more method org.apache.commons.lang3.exception.ExceptionUtils.hasCause
Upvotes: 1