我正在使用一些REST / jackson功能包装遗留代码。特别是假设我有一个名为LegacyObject的接口
interface LegacyObject {
Integer getAge(); //could throw UnsupportedOperationException
String getDesc();
String getName(); //May throw RuntimeException
//about 200+ other methods.
}
该实现是遗留类,并假设无法更改。我的REST服务有一个端点,可以将LegacyObject转换为JSON。唯一的问题是,只要其中一个getter抛出异常,此转换就会完全失败。我需要的是一个像下面的json(假设getAge(),getDesc()工作正常,但getName()抛出runtimeexception)
{"age": 40, "desc": "some description", "unsupportedFields": ["name"]}
基本上是一种捕获序列化失败的所有字段然后在最后报告的方法。
类似拦截器的东西可能对我有用,但是如果有人有一些代码示例会很棒!
答案 0 :(得分:1)
由于界面中有200多种方法,因此在Proxies的解决方案下面。
此代码不保证最后调用“getUnsupportedFields”方法(因此仍可能发生一些异常)
public interface LegacyObject {
Integer getAge(); //could throw UnsupportedOperationException
String getDesc();
String getName(); //May throw RuntimeException
//about 200+ other methods.
}
import java.util.List;
public interface ExtendedLegacyObject extends LegacyObject {
List<String> getUnsupportedFields();
}
public class ExceptionLegacyObject implements LegacyObject {
@Override
public Integer getAge() {
return 40;
}
@Override
public String getDesc() {
return "some description";
}
@Override
public String getName() {
throw new RuntimeException();
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
public class LegacyObjectHandler implements InvocationHandler {
private static final Logger LOG = Logger.getLogger(LegacyObjectHandler.class);
private final List<String> unsupportedFields = new ArrayList<>();
private final LegacyObject legacyObject;
public LegacyObjectHandler(LegacyObject legacyObject) {
this.legacyObject = legacyObject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("getUnsupportedFields".equals(method.getName())) {
return unsupportedFields;
} else {
try {
return method.invoke(legacyObject, args);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
LOG.error(cause.getMessage(), cause);
unsupportedFields.add(method.getName());
Class<?> returnType = method.getReturnType();
if (returnType.isPrimitive()) {
if (returnType.isAssignableFrom(boolean.class)) {
return false;
} else if (returnType.isAssignableFrom(byte.class)) {
return (byte) 0;
} else if (returnType.isAssignableFrom(short.class)) {
return (short) 0;
} else if (returnType.isAssignableFrom(int.class)) {
return 0;
} else if (returnType.isAssignableFrom(long.class)) {
return 0L;
} else if (returnType.isAssignableFrom(float.class)) {
return 0F;
} else if (returnType.isAssignableFrom(double.class)) {
return 0D;
} else if (returnType.isAssignableFrom(char.class)) {
return (char) 0;
} else {
return null;
}
} else {
return null;
}
}
}
}
}
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.lang.reflect.Proxy;
public class JacksonTest {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ExceptionLegacyObject exceptionLegacyObject = new ExceptionLegacyObject();
ExtendedLegacyObject proxy = (ExtendedLegacyObject) Proxy.newProxyInstance(
LegacyObject.class.getClassLoader(),
new Class[] { ExtendedLegacyObject.class },
new LegacyObjectHandler(exceptionLegacyObject)
);
System.out.println(mapper.writeValueAsString(proxy));
}
}
答案 1 :(得分:0)
我使用了@toongeorges上面提到的变体。这是一个实用程序类,它将执行“异常安全”转换为JSON。返回的JSON中将有一个名为“exceptionMessages”的额外元素,其中包含json序列化失败的属性(如果它不是Java bean属性,则包含方法名称)。如果该样式更适合你,可以更改为对象返回一对JsonNode,为exceptionMessages返回一对
import static java.util.stream.Collectors.toMap;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.apache.commons.lang3.exception.ExceptionUtils;
public abstract class JsonUtils {
private static ObjectMapper mapper = new ObjectMapper();
/**
* This is only useful in the context of converting a object whose methods could throw exceptions
* into JSON. By default a "getName" method that throws an exception will fail the whole
* serialization however with this method such exceptions will be swallowed and there will be a
* "exceptionMessages" element in the returned JSON which contains all failures
*
* To be used only when working with legacy code.
*/
@SuppressWarnings("unchecked")
public static <U> ObjectNode exceptionSafeWrite(Class<U> sourceClazz, U obj, boolean prettyPrint) {
GuardedInvocationHandler handler = new GuardedInvocationHandler(obj);
U proxiedObject = (U) Proxy
.newProxyInstance(sourceClazz.getClassLoader(), new Class<?>[]{sourceClazz}, handler);
ObjectNode originalNode = mapper.convertValue(proxiedObject, ObjectNode.class);
ObjectNode exceptionMessages = mapper.convertValue(handler.getExceptionMessagesForJson(), ObjectNode.class);
originalNode.put("exceptionMessages", exceptionMessages);
return originalNode;
}
private static class GuardedInvocationHandler implements InvocationHandler {
private final Object target;
private Map<Method, Throwable> exceptionMap = new LinkedHashMap<>();
private Map<Method, String> methodToPropertyNameMap;
private GuardedInvocationHandler(Object target) {
this.target = target;
this.methodToPropertyNameMap = methodToPropertyNameMap(target.getClass());
}
private static Map<Method, String> methodToPropertyNameMap(Class<?> clazz) {
try {
return Stream.of(Introspector.getBeanInfo(clazz).getPropertyDescriptors())
.collect(toMap(d -> d.getReadMethod(), d -> d.getName()));
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
exceptionMap.put(method, e.getTargetException());
return null;
} catch (Exception e) {
exceptionMap.put(method, e);
return null;
}
}
public Map<String, String> getExceptionMessagesForJson() {
return exceptionMap.entrySet().stream().collect(
toMap(e -> methodToPropertyNameMap.getOrDefault(e.getKey(), e.getKey().getName()),
e -> ExceptionUtils.getMessage(e.getValue())));
}
}
}