io.jsonwebtoken.impl.lang.PropagatingExceptionFunction Maven / Gradle / Ivy
/*
* Copyright (C) 2022 jsonwebtoken.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jsonwebtoken.impl.lang;
import io.jsonwebtoken.lang.Assert;
import io.jsonwebtoken.lang.Classes;
import io.jsonwebtoken.lang.Supplier;
import java.lang.reflect.Constructor;
public class PropagatingExceptionFunction implements Function {
private final CheckedFunction function;
private final Function msgFunction;
private final Class clazz;
public PropagatingExceptionFunction(Function f, Class exceptionClass, String msg) {
this(new DelegatingCheckedFunction<>(f), exceptionClass, new ConstantFunction(msg));
}
public PropagatingExceptionFunction(CheckedFunction f, Class exceptionClass, final String msg) {
this(f, exceptionClass, new ConstantFunction(msg));
}
public PropagatingExceptionFunction(CheckedFunction fn, Class exceptionClass, final Supplier msgSupplier) {
this(fn, exceptionClass, new Function() {
@Override
public String apply(T t) {
return msgSupplier.get();
}
});
}
public PropagatingExceptionFunction(CheckedFunction f, Class exceptionClass, Function msgFunction) {
this.clazz = Assert.notNull(exceptionClass, "Exception class cannot be null.");
this.msgFunction = Assert.notNull(msgFunction, "msgFunction cannot be null.");
this.function = Assert.notNull(f, "Function cannot be null");
}
@SuppressWarnings("unchecked")
public R apply(T t) {
try {
return function.apply(t);
} catch (Exception e) {
if (clazz.isAssignableFrom(e.getClass())) {
throw clazz.cast(e);
}
String msg = this.msgFunction.apply(t);
if (!msg.endsWith(".")) {
msg += ".";
}
msg += " Cause: " + e.getMessage();
Class clazzz = (Class) clazz;
Constructor ctor = Classes.getConstructor(clazzz, String.class, Throwable.class);
throw Classes.instantiate(ctor, msg, e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy