How to handle exceptions in sleep mode?

I use hibernate and this looks for most of my methods:

public boolean insertUser(User user) { Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); session.save(user); session.getTransaction().commit(); } catch (HibernateException he) { session.getTransaction().rollback(); return false; } finally { if (session != null) { session.close(); } } return true; } 

But I would like to handle exceptions in the best possible way to give the best message to the user, for example: when I have a duplicate in my table, etc.

What do you guys recommend?

Regards, Walter Enrique.

+4
source share
2 answers
  • Whatever you do, do not swallow exceptions. In your code, you will never know what an exception is. So flip it / wrapper. And write it down somewhere (maybe not necessarily in the code above)

  • create a general exception handler at the web level - maybe a Filter or 404 page (and configure it in web.xml). And show the same message to users regardless of the exception. Users do not care if this is a missing column or an incorrect data type. Give them a nice message that you are sorry and you will investigate.

  • Also consider the declarative transaction processing proposed by spring.

+2
source

Instead of returning true or false, you can throw a business exception from your own (perhaps a hierarchy over a RuntimeException, which makes sense for your problem).

How do you discover which particular problem was another problem. You can deploy your own translation compiler, which, depending on the SQLException, will throw an exception (specific to your business).

Note that for this particular method that you represent, it would be better to query the database first for the key to exist and throw a UserAlreadyExistsException (or something else).

+1
source

Source: https://habr.com/ru/post/1346351/


All Articles