Reputation: 1892
Can I cancel delete event using onBeforeDelete
method of MongoGenreCancelDeleteEventsListener
? If yes then how?
@Component
public class MongoGenreCancelDeleteEventsListener extends AbstractMongoEventListener<Genre> {
private final BookRepository bookRepository;
@Override
public void onBeforeDelete(BeforeDeleteEvent<Genre> event) {
super.onBeforeDelete(event);
// check conditions and cancel delete
}
}
Upvotes: 2
Views: 148
Reputation: 740
I know this is an old question, but I had the same issue and I found a solution.
Basically, your code should become like this:
@Component
public class MongoGenreCancelDeleteEventsListener extends AbstractMongoEventListener<Genre> {
private BookRepository bookRepository;
@Override
public void onBeforeDelete(BeforeDeleteEvent<Genre> event) {
super.onBeforeDelete(event);
boolean abort = false;
//do your check and set abort to true if necessary
if (abort) {
throw new IllegalStateException(); //or any exception you like
}
}
}
The thrown exception prevents the operation from going further and it stops there. Also, the exception gets propagated to the caller (anyway, it is wrapped inside a UndeclaredThrowableException
, so this is what you should catch; make sure that the wrapped exception is indeed the one you've thrown by calling the getCause()
method).
Hope it helps.
Upvotes: 1