Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch only first N lines of a Stack Trace

I have a Factory method that returns an object from a ID call.

Mock code:

public static Object getById(String id) {
    Object o = CRUD.doRecovery(Class, id);
    if(o == null) {
         printLogMessage("recovery by ID returned Null: " + id);
         // would really like to show only a few lines of stack trace.
    }
    return o;
}

How can I show only the first N lines of the stack trace (so I know the caller of the method) without dumping the whole stack trace on the log or having to rely on external libs?

like image 675
Mindwin Avatar asked Feb 11 '14 15:02

Mindwin


1 Answers

You can use the ex.getStackTrace() to get the stack elements, the StackTraceElement contains one line of the full stacks, then print print what ever you want.

StackTraceElement[] elements = ex.getStackTrace();
print(elements[0]);
like image 88
Salah Avatar answered Oct 03 '22 16:10

Salah