com.newpixelcoffee.odin.exceptions.OdinAdapterException Maven / Gradle / Ivy
package com.newpixelcoffee.odin.exceptions;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* Throw by odin if an error occur during the read or write method of an adapter. Each layer of adapter throw a new AdapterException with the object type and field to have the path of the error
* @author DocVander
*/
public class OdinAdapterException extends RuntimeException {
private String message;
private String type;
private String field;
public OdinAdapterException(String type, String field, String message, Throwable cause) {
super(message, cause);
this.message = message;
this.type = type;
this.field = field;
}
public boolean isThrownByAdapter(String type) {
return type.equals(this.type) && field != null;
}
@Override
public String getMessage() {
return message + ". type: " + type + (field != null ? " field: " + field : "");
}
@Override
public void printStackTrace(PrintWriter writer) {
synchronized (writer) {
writer.println(getClass().getName() + ": " + message);
writer.println("\tPath:");
odinExceptionPrinter(new WrappedPrintWriter(writer), this);
}
}
@Override
public void printStackTrace(PrintStream stream) {
synchronized (stream) {
stream.println(getClass().getName() + ": " + message);
stream.println("\tPath:");
odinExceptionPrinter(new WrappedPrintStream(stream), this);
}
}
private void odinExceptionPrinter(OdinPrintStreamOrWriter s, OdinAdapterException e) {
s.println("\t\tat " + e.type + (e.field != null ? " field: " + e.field : ""));
Throwable cause = e.getCause();
if (cause instanceof OdinAdapterException && ((OdinAdapterException) cause).message.equals(message))
odinExceptionPrinter(s, (OdinAdapterException) cause);
else
otherThrowablePrinter(s, cause);
}
private void otherThrowablePrinter(OdinPrintStreamOrWriter s, Throwable e) {
s.println("\tCaused by: " + e);
StackTraceElement[] trace = e.getStackTrace();
int i = 0;
for (StackTraceElement traceElement : trace) {
if (i > 4 && traceElement.getClassName().startsWith("com.newpixelcoffee.odin.internal")) {
s.println("\t\t... " + (trace.length - i) + " more");
break;
}
s.println("\t\tat " + traceElement);
i++;
}
if (e.getCause() != null)
otherThrowablePrinter(s, e.getCause());
}
// COPY OF JAVA THROWABLE PRINTER
private abstract static class OdinPrintStreamOrWriter {
abstract void println(Object o);
}
private static class WrappedPrintStream extends OdinPrintStreamOrWriter {
private final PrintStream printStream;
WrappedPrintStream(PrintStream printStream) {
this.printStream = printStream;
}
void println(Object o) {
printStream.println(o);
}
}
private static class WrappedPrintWriter extends OdinPrintStreamOrWriter {
private final PrintWriter printWriter;
WrappedPrintWriter(PrintWriter printWriter) {
this.printWriter = printWriter;
}
void println(Object o) {
printWriter.println(o);
}
}
}