Naman Gala
Naman Gala

Reputation: 4692

which option is better to get the method name of executing method

I am trying to log method name in exception catch block.

I have found following solutions from Getting the name of the current executing method

String name = new Object(){}.getClass().getEnclosingMethod().getName();

or

String name = Thread.currentThread().getStackTrace()[1].getMethodName();

or

String name = new Exception("is not thrown").getStackTrace()[0].getMethodName();

Which option is better to get method name in catch block?

Note: I want to use the code in every catch block of my application, So I am asking for the solution which has less overhead.

Thanks.

Update:

Following steps I am doing to handle the exception

1. Catching the exception in try catch block
2. Wrapping that exception in MyException.
3. Setting method name, class name and user defined message. (For this step I have asked this question)
4. Throwing back the MyException.
5. Finally handling MyException in Controller.

Using Spring AOP I can achieve above scenario. But how will I set user defined message in MyException?

Upvotes: 2

Views: 854

Answers (1)

Panther
Panther

Reputation: 3339

If you are writing same code in after every method like logging entering , existing the method or if you have same kind of exception handling for each method, then you should go fore some aspect oriented framework like aspectj and write code at one place instead of calling from everywhere.

In Aspect you need to define pointcuts and you will get your class name and method name from parameters. You can use simple aspectj framework or Spring AOP if you are using Spring. Apart from that there are other frameworks for aspect oriented coding.

You just need to define some wildcard entries for your methods and classes and your aspect code automatically will be called after method calls.

http://www.javacodegeeks.com/2014/02/applying-aspect-oriented-programming.html

http://www.javatpoint.com/spring-aop-tutorial

Upvotes: 1

Related Questions