I try to save a duplicate book to my Book domain class for testing. I have a try-catch(Exception ex) to get the error.
BookService bookService
try {
def book = new Book()
book.id = 'Lord of the Flies'
bookSerivce.save(book)
def anotherBook = new Book()
anotherBook.id = 'Lord of the Flies'
bookService.save(anotherBook)
} catch (Exception ex) {
System.out.println(ex.getMessage())
}
I use ex.getMessage(). I am getting this error message. This one is pretty much useless.
could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
On the other hand, I am getting this error message from the command prompt console. This one I can use. It clearly says that I already have a book called 'Lord of the Flies' in the database.
2020-11-02 14:46:39.790 ERROR --- [eduler_Worker-1] o.h.engine.jdbc.spi.SqlExceptionHelper : (conn=665) Duplicate entry 'Lord of the Flies' for key 'PRIMARY'
I understand I should not use the catch-all Exception. I will need to use a more specific Exception class. I already tried catch (SQLException ex) but it did not catch the error. I also tried some others Exception classes but they didn't catch the error either.
It also looks like book.save() and bookSerive.save(book) throw a different Exception.
Would you show me which Exception class I can use in the catch() function to capture the correct error please?
Thanks!
The question and the comments below it aren't especially clear to me but something to investigate is the root cause of the exception:
BookService bookService
try {
def book = new Book()
book.id = 'Lord of the Flies'
bookSerivce.save(book)
def anotherBook = new Book()
anotherBook.id = 'Lord of the Flies'
bookService.save(anotherBook)
} catch (Exception ex) {
System.out.println(ex.getMessage())
Throwable t = ex.getCause()
if(t) {
// interrogate t as the root cause
}
}