Grails 不知道如何获取异常
Grails Don't Know How To Get Exception
我尝试将一本重复的书保存到我的图书域 class 以进行测试。我有一个 try-catch(Exception ex) 来获取错误。
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())
}
我使用ex.getMessage()。我收到此错误消息。这个基本没什么用。
could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
另一方面,我从命令提示符控制台收到此错误消息。这个我可以用。它清楚地表明我已经在数据库中有一本名为 'Lord of the Flies' 的书。
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'
我知道我不应该使用包罗万象的异常。我将需要使用更具体的异常 class。我已经尝试过 catch (SQLException ex) 但它没有捕获到错误。我还尝试了其他一些异常 classes 但他们也没有发现错误。
看起来 book.save() 和 bookSerive.save(book) 抛出不同的异常。
你能告诉我我可以在 catch() 函数中使用哪个异常 class 来捕获正确的错误吗?
谢谢!
这个问题及其下面的评论对我来说不是特别清楚,但需要调查的是异常的根本原因:
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
}
}
我尝试将一本重复的书保存到我的图书域 class 以进行测试。我有一个 try-catch(Exception ex) 来获取错误。
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())
}
我使用ex.getMessage()。我收到此错误消息。这个基本没什么用。
could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
另一方面,我从命令提示符控制台收到此错误消息。这个我可以用。它清楚地表明我已经在数据库中有一本名为 'Lord of the Flies' 的书。
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'
我知道我不应该使用包罗万象的异常。我将需要使用更具体的异常 class。我已经尝试过 catch (SQLException ex) 但它没有捕获到错误。我还尝试了其他一些异常 classes 但他们也没有发现错误。
看起来 book.save() 和 bookSerive.save(book) 抛出不同的异常。
你能告诉我我可以在 catch() 函数中使用哪个异常 class 来捕获正确的错误吗?
谢谢!
这个问题及其下面的评论对我来说不是特别清楚,但需要调查的是异常的根本原因:
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
}
}