Reputation: 265
Let's say I have this exception showing in the console:
java.nio.file.DirectoryNotEmptyException: /path/here/directory
at java.base/sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:466)
at java.base/sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:267)
at java.base/java.nio.file.Files.move(Files.java:1421)
at class.method(class.java:158)
at class.method(class.java:234)
at class.method(class.java:23)
...
...
... more lines ...
How could I extract the first N lines INCLUDING java.nio.file.DirectoryNotEmptyException: /path/here/directory
?
I have written this to get the first 2 lines:
String stackTrace = "";
if (error != null ) {
StackTraceElement[] stackTraceElements = error.getStackTrace();
stackTrace = stackTraceElements[0].toString() + stackTraceElements[1].toString();
}
But this only yielded:
at java.base/sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:466)at java.base/sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:267)
I was under the impression that StackTraceElements[0]
would be the java.nio.file.DirectoryNotEmptyException: /path/here/directory
but it wasn't and i have no idea how to get the proper amount of N lines to include this.
Upvotes: 0
Views: 1216
Reputation: 15136
A simple way would be to concatenate the error message with the toString of each stack trace entry. Use Arrays.stream()
with limit(N)
to get you the required number of entries in the stack trace, convert them to String and join with line separator.
Try a variation of this:
Exception ex = new Exception("File not found message");
int depth = 3;
String stackN = Arrays.stream(ex.getStackTrace()).limit(depth)
.map(String::valueOf)
// .map(s -> " at "+s)
.collect(Collectors.joining(System.lineSeparator()));
String all = ex.toString()+System.lineSeparator() + stackN;
System.out.println(all);
You may want to experiment with different formatting or indentation (tabs / space prefix etc) which could be achieved with extra map step inserted into the stream, such as .map(s -> " "+s)
Upvotes: 0
Reputation: 481
Print the Exception also:
public class Tracer
{
public static void main (String[] args)
{
Tracer app = new Tracer ();
app.execute ();
}
private void execute ()
{
try
{
failure (5);
}
catch (Exception e)
{
StackTraceElement[] stackTraceElements = e.getStackTrace ();
StringBuilder builder = new StringBuilder ();
builder.append (e);
builder.append ("\n");
for (int i = 0; i < 3; i++)
{
builder.append (stackTraceElements[i].toString ());
builder.append ("\n");
}
System.out.println (builder);
}
}
private void failure (int n) throws Exception
{
if (n <= 0)
{
throw new Exception ("Exception message");
}
else
{
failure (n - 1);
}
}
}
Upvotes: 1