Created
May 20, 2014 17:50
-
-
Save oleksiyp/1c6b2203c52596dcfc5b to your computer and use it in GitHub Desktop.
Making UncaughtExceptionHandler user friendly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.silverrail.utils; | |
import java.io.StringWriter; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class UncaughtExceptionHandlerForHumans implements Thread.UncaughtExceptionHandler { | |
@Override | |
public void uncaughtException(Thread t, Throwable e) { | |
List<Throwable> chain = new ArrayList<>(); | |
Throwable cause = e; | |
while (cause != null) { | |
chain.add(cause); | |
cause = cause.getCause(); | |
} | |
StringWriter buf = new StringWriter(); | |
buf.append(String.format(" BADABUM in thread '%s'%n", t.getName())); | |
for (Throwable throwable : chain) { | |
buf.append(String.format(" ||%n")); | |
buf.append(String.format(" \\/%n")); | |
StackTraceElement[] stackTrace = throwable.getStackTrace(); | |
if (stackTrace != null && stackTrace.length > 0) { | |
StackTraceElement topElement = stackTrace[0]; | |
buf.append(String.format("%s(%d): %s%n", | |
topElement.getFileName(), | |
topElement.getLineNumber(), | |
throwable.getMessage())); | |
} else { | |
buf.append(String.format("%s%n", throwable.getMessage())); | |
} | |
} | |
System.out.flush(); | |
System.err.println(buf); | |
} | |
public static void set() { | |
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandlerForHumans()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment