
org.rajivprab.cava.exception.CheckedExceptionWrapper Maven / Gradle / Ivy
package org.rajivprab.cava.exception;
/**
* Wrapper for checked exceptions, that looks as similar as reasonably possible to the underlying exception.
*
* Any stack-traces will show the stack-trace for where the underlying exception was thrown from,
* and not where the CheckedExceptionWrapper was wrapped and thrown from.
* Thesis: Including the stack-trace for wrapping-and-rethrowing just adds noise, with minimal debug help.
*
* The cause will match the underlying exception's cause.
*
* toString() will prepend the current class-name, to the underlying's toString.
* This enables better debugging of the specific exception type that was thrown, and/or needs to be caught.
*
* Created by rprabhakar on 12/15/15.
*/
public class CheckedExceptionWrapper extends RuntimeException {
private final Throwable underlying;
// If argument is a RunTimeException, returns it as is. Else, wraps it in a CheckedExceptionWrapper
public static RuntimeException wrapIfNeeded(Throwable throwable) {
return throwable instanceof RuntimeException ? (RuntimeException) throwable : wrap(throwable);
}
// Always wraps the argument in a CheckedExceptionWrapper. Useful for consistency in catching it
public static CheckedExceptionWrapper wrap(Throwable throwable) {
return new CheckedExceptionWrapper(throwable);
}
protected CheckedExceptionWrapper(Throwable underlying) {
super(underlying.getMessage(), underlying.getCause(), true, true);
setStackTrace(underlying.getStackTrace());
this.underlying = underlying;
}
// getCause() returns the underlying exception's cause,
// not the underlying exception itself. To get the underlying exception, use this method
public Throwable getUnderlying() {
return underlying;
}
@Override
public String toString() {
return getClass().getCanonicalName() + ": " + underlying.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof CheckedExceptionWrapper) {
CheckedExceptionWrapper that = (CheckedExceptionWrapper) o;
return getUnderlying().equals(that.getUnderlying());
} else {
return getUnderlying().equals(o);
}
}
@Override
public int hashCode() {
return underlying.hashCode();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy