happybuddha
happybuddha

Reputation: 1358

How to do common Exception handling

Lets say I have about a hundred classes with this method signature, which is the only entry exit method for that class :

public Map<String,Object> doSome(Map arg1, map arg2)

and within the method body there is a try/catch block. The catch block catches Exception and rethrows a custom exception. Earlier the program would just abandon in the catch block. Now I need to be able to return a Map which has a key value like ("Exception", "Some went bad in this class"). One way to do it is to make an additional method within this doSome method (and push the current code into the new one) and surround this method call with a try/catch and in the catch block catch the custom exception and write a generic method to populate the returning map
What would be the best way to achieve this for all of those 100+ classes ?
I am wondering if such a thing can be achieved using Spring AOP ? But most of the spring advices I come across dont allow returning of values (meaning the control never bubbles back to where the exception was thrown from).
It would be great if someone can point me to specific examples.

Upvotes: 0

Views: 186

Answers (2)

Lavanya
Lavanya

Reputation: 319

May be you can try Spring AOP type "After throwing advice - runs after the method throws an exception" You can look at the simple example here : http://www.mkyong.com/spring/spring-aop-examples-advice/

Upvotes: 0

Duncan Jones
Duncan Jones

Reputation: 69329

This sounds like something that can be solved with some functionality provided by a parent class.

Have each of your 100 classes (really, 100??!) extend an abstract parent class. Have the parent class define the doSomething method:

public Map<String,Object> doSome(Map arg1, Map arg2) {

  try {
    doSomething(arg1, arg2);
  } catch (Exception e) {
    // clever handling here
  }
}

Make sure the doSomething() method is defined as an abstract method in ExceptionHandler. Of course, better method names would be welcome.

Each of the subclasses would implement their own variation of doSomething().

Upvotes: 1

Related Questions