3

I am using spring's @ControllerAdvice and @ExceptionHandler for exception handling. Any method throws custom exception from Controller and corresponding @ExceptionHandler handle it. If Runtime exception occurs(eg any HibernateException) then it will throw Runtime Exception and I dont have any @ExceptionHandler for RuntimeExceptions.

My question is how to handle any runtime exception? do I need to add @ExceptionHandler for every Exception that is thrown by controller? I dont want create an Generic ExceptionHandler for Exception.class because I have to send different error code according to exception occured.

one way to do it add try catch block in Controller and then throw the custom exception from catch block? or is there any another better way?

All @ExceptionHandlers are inside @ControllerAdvice class.

Suraj
  • 1,625
  • 1
  • 15
  • 33
  • You handle runtime exceptions the same way you handle checked exceptions. Add an ExceptionHandler for HibernateException, and it will handle HibernateExceptions thrown by the controller. – JB Nizet Jan 21 '16 at 08:10
  • @JBNizet thanks for comment. – Suraj Jan 21 '16 at 09:23
  • 1
    I am getting MySQLIntegrityConstraintViolationException due to duplicate entry in db. if I create separate ExceptionHandler for this Exception and return any message eg " record already exists", but it may be possible that the same Exception has been thrown due to another cause in which case my message would not be appropriate. how to handle this situation? – Suraj Jan 21 '16 at 09:32
  • 1
    The message should be generic, and shown as last resort. You should rather try to avoid the exception in the first place, by checking before inserting the record that it doesn't exist yet. – JB Nizet Jan 21 '16 at 10:52

1 Answers1

3

the alternative is don't catch Exception in Controller. catch all Exception in service layer and throw a custom Exception eg. if you persisting a record failed, throw DatabaseException with message. see below method:

Student persist(Student object){
   try{
      studentDao.insert(object);
   }catch(HibernateException e){
      throw new DatabaseException("database operation failed!");
   }
   return student;
}

from you exception handler method you can get the message. this way you can set different message on different Exception.

Jaymin Panchal
  • 2,797
  • 2
  • 27
  • 31