You can either catch a common JDBCException
:
try { userDao.save(user); //might throw exception } catch(JDBCException e) { //Error during hibernate query }
or you can also catch one of the more specific subclasses of JDBCException
, such as ConstraintViolationException
or JDBCConnectionException
:
try { userDao.save(user); //might throw exception } catch(ConstraintViolationException e) { //Email Address already exists } catch(JDBCConnectionException e) { //Lost the connection }
and using the e.getCause()
method, you can get the base SQLException
and parse it further:
try { userDao.save(user); //might throw exception } catch(JDBCException e) { SQLException cause = (SQLException) e.getCause(); //evaluate cause and find out what was the problem System.out.println(cause.getMessage()); }
To print, for example: Duplicate entry 'UserTestUsername' for key 'username'
lanoxx
source share