Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Runtime Exceptions are handled by Spring ExceptionHandler

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.

like image 247
Suraj Avatar asked Aug 29 '26 03:08

Suraj


1 Answers

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.

like image 131
Anand Kumar Avatar answered Aug 30 '26 21:08

Anand Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!