From 4a0da3fa6859c78d5f2e06533e448f40e973c74f Mon Sep 17 00:00:00 2001 From: zhou-hao Date: Fri, 27 Nov 2026 16:06:26 +0800 Subject: [PATCH 1/5] =?UTF-8?q?fix(bean)!:=20=E8=A7=84=E8=8C=83=20Map=20?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E5=B9=B6=E6=94=AF=E6=8C=81=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=20SPI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 源属性仅求值一次,Bean 转 Map 时排除 transient 字段及 JavaBeans Transient 属性,保留只读源属性与按名称取值能力。 异常直接转 Map 时输出类型、消息、完整堆栈文本和国际化信息, 通过延迟字段 SPI 支持上层替换异常映射及堆栈精简。 BREAKING CHANGE: Bean 转 Map 不再导出 transient 属性;Throwable 转 Map 改为固定描述字段,不再枚举 cause、suppressed 等任意属性。 --- hsweb-core/README.md | 10 +- .../bean/DefaultExceptionToMapConverter.java | 40 ++++ .../web/bean/ExceptionToMapConverter.java | 18 ++ .../web/bean/FastBeanCopier.java | 55 +++++- .../bean/FastBeanCopierExceptionSpiTest.java | 105 ++++++++++ .../web/bean/FastBeanCopierExceptionTest.java | 143 ++++++++++++++ .../web/bean/FastBeanCopierReadOnceTest.java | 183 ++++++++++++++++++ .../web/bean/FastBeanCopierTransientTest.java | 135 +++++++++++++ 8 files changed, 682 insertions(+), 7 deletions(-) create mode 100644 hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionToMapConverter.java create mode 100644 hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionToMapConverter.java create mode 100644 hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java create mode 100644 hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionTest.java create mode 100644 hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierReadOnceTest.java create mode 100644 hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierTransientTest.java diff --git a/hsweb-core/README.md b/hsweb-core/README.md index 0ef54d7e8..8b75de977 100644 --- a/hsweb-core/README.md +++ b/hsweb-core/README.md @@ -27,7 +27,15 @@ 实现位于 `hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java`,使用独立的 `PropertyUtilsBean` 和内省扩展点,不修改全局 BeanUtils 配置,复用现有代码生成、类型转换和缓存。 -访问器回归由 `FastBeanCopierBeanTest`、`FastBeanCopierReadOnlyTest` 和 `FastBeanCopierTest` 覆盖,包括只读源属性、目标可写边界、不同访问器风格、继承泛型、忽略属性、record、全局配置隔离及静态访问器排除。 +Bean 属性复制每次只读取一次实际参与复制的源属性,空值保持现有跳过写入的语义;include/ignore 排除的属性不读取,getter 抛出的异常继续传播。Bean 转普通 Map 保持浅复制,嵌套的 Throwable 保留原引用,不自动展开、丢弃或转成字符串。 + +Bean/record 转 Map 时排除 `transient` 字段(包含继承字段)及 JavaBeans `java.beans.Transient` 标记的属性,排除发生在调用 getter 前,显式 include 也不会导出这些属性。`@Transient(false)` 不排除属性,但不能覆盖字段上的 `transient`。此规则不影响 Bean→Bean、Map→Bean、Bean→record、Map→Map 和 `getProperty` 按名称取值。 + +直接将 Throwable 转 Map(包括 `DEFAULT_CONVERT.convert(error, Map.class, ...)`)使用固定描述字段:`type` 为完整类名,`message` 为异常消息,`detail` 为含 cause/suppressed 的完整堆栈文本;`I18nSupportException` 另提供 `i18nCode`、`args`,`BusinessException` 另提供业务 `code`、`status`。参数保持浅复制及原类型;空值跳过,不再枚举异常的其他 getter 或携带原始 cause/suppressed/stackTrace 对象。include/ignore 在取值前应用,排除 detail 时不生成堆栈,值转换仍使用调用方的 Converter。Map 用于错误描述,异常的真实类型还原不依赖类名反射实例化。 + +可在 `META-INF/services/org.hswebframework.web.bean.ExceptionToMapConverter` 注册自定义异常映射实现。首次异常转换时使用线程上下文 ClassLoader 发现的首个实现,每个运行环境应只注册一个;无实现时回退 `DefaultExceptionToMapConverter`。实例按 copier 的 ClassLoader 复用,自定义实现应无状态或线程安全。SPI 按字段提供延迟 Supplier,由 copier 统一过滤、读取及转换;继承默认实现并覆盖 `getDetail(Throwable)` 可复用上层平台的栈精简逻辑,自定义栈处理需保留循环引用处理,无需改变其他字段或引入反向依赖。 + +访问器回归由 `FastBeanCopierBeanTest`、`FastBeanCopierReadOnlyTest`、`FastBeanCopierReadOnceTest`、`FastBeanCopierTransientTest` 和 `FastBeanCopierTest` 覆盖,包括只读源属性、单次取值、导出排除规则、目标可写边界、不同访问器风格、继承泛型、忽略属性、record、全局配置隔离及静态访问器排除。`FastBeanCopierExceptionTest` 与 `FastBeanCopierExceptionSpiTest` 覆盖异常描述、循环 cause、国际化字段、值转换和 SPI 发现及延迟取值。 约定: 如果属性类实现了`Cloneable`接口,在复制的时候将调用`clone`方法.所以如果你实现了`Cloneable`接口,就必须重写`clone`方法并且为`public`修饰的. diff --git a/hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionToMapConverter.java b/hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionToMapConverter.java new file mode 100644 index 000000000..9ea65685e --- /dev/null +++ b/hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionToMapConverter.java @@ -0,0 +1,40 @@ +package org.hswebframework.web.bean; + +import org.hswebframework.web.exception.BusinessException; +import org.hswebframework.web.exception.I18nSupportException; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +/** + * 提供异常描述及国际化信息,不对异常的任意 getter 进行内省。 + * detail 使用完整堆栈文本,避免在 Map 中保留 cause/suppressed 对象图。 + */ +public class DefaultExceptionToMapConverter implements ExceptionToMapConverter { + + @Override + public void convert(Throwable source, BiConsumer> properties) { + properties.accept("type", () -> source.getClass().getName()); + properties.accept("message", source::getMessage); + properties.accept("detail", () -> getDetail(source)); + if (source instanceof I18nSupportException i18n) { + properties.accept("i18nCode", i18n::getI18nCode); + properties.accept("args", i18n::getArgs); + } + if (source instanceof BusinessException business) { + properties.accept("code", business::getCode); + properties.accept("status", business::getStatus); + } + } + + /** + * 覆盖此方法可使用上层平台的栈精简能力。 + */ + protected String getDetail(Throwable source) { + StringWriter writer = new StringWriter(); + source.printStackTrace(new PrintWriter(writer)); + return writer.toString(); + } +} diff --git a/hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionToMapConverter.java b/hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionToMapConverter.java new file mode 100644 index 000000000..f799a9acc --- /dev/null +++ b/hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionToMapConverter.java @@ -0,0 +1,18 @@ +package org.hswebframework.web.bean; + +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +/** + * 异常转 Map 的字段提供者,通过 {@link java.util.ServiceLoader} 注册。 + * + *

字段值必须延迟到 Supplier 被调用时读取,使 copier 能在读取前应用 include/ignore。 + * copier 负责空值跳过和值转换;提供者不应提前生成堆栈等诊断信息。 + * 自定义实现可继承 {@link DefaultExceptionToMapConverter}。 + * + * @see FastBeanCopier + */ +public interface ExceptionToMapConverter { + + void convert(Throwable source, BiConsumer> properties); +} diff --git a/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java b/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java index 325564a6e..541f45eef 100644 --- a/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java +++ b/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java @@ -22,6 +22,7 @@ import java.beans.Introspector; import java.beans.PropertyDescriptor; +import java.beans.Transient; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -135,7 +136,7 @@ public static Object getProperty(Object source, String key) { return ((Map) source).get(key); } SingleValueMap map = new SingleValueMap<>(); - copy(source, map, include(key)); + getCopier(source, map, true).copy(source, map, include(key), DEFAULT_CONVERT); return map.getValue(); } @@ -169,6 +170,20 @@ public static T copy(S source, T target, Converter converter, Set // record 不可变,无法写入已存在实例;这里按组件名重新构造并返回新实例。 return (T) copyToRecord(source, (Class) getUserClass(target), converter, ignore); } + if (source instanceof Throwable && target instanceof Map) { + ExceptionConverterHolder.INSTANCE.convert((Throwable) source, (name, supplier) -> { + if (!ignore.contains(name)) { + Object value = supplier.get(); + if (value != null) { + Object converted = converter.convert(value, Object.class, EMPTY_CLASS_ARRAY); + if (converted != null) { + ((Map) target).put(name, converted); + } + } + } + }); + return target; + } if (source instanceof Map && target instanceof Map) { if (CollectionUtils.isEmpty(ignore)) { ((Map) target).putAll(((Map) source)); @@ -188,6 +203,13 @@ public static T copy(S source, T target, Converter converter, Set return target; } + private static class ExceptionConverterHolder { + private static final ExceptionToMapConverter INSTANCE = ServiceLoader + .load(ExceptionToMapConverter.class) + .findFirst() + .orElseGet(DefaultExceptionToMapConverter::new); + } + static T copyToRecord(S source, Class target, Converter converter, String... ignore) { Set ignored = (ignore == null || ignore.length == 0) ? Collections.emptySet() @@ -228,6 +250,10 @@ private static RecordCopier createRecordCopier(Class source, Class target) } static Class getUserClass(Object object) { + // 单属性读取使用独立的 copier,不应用 Map 导出时的属性过滤。 + if (object instanceof SingleValueMap) { + return SingleValueMap.class; + } if (object instanceof Map) { return Map.class; } @@ -424,6 +450,9 @@ private static String createCopierCode(Class source, Class target) { } } else if (targetIsMap) { sourceProperties = createProperty(source, false); + if (target != SingleValueMap.class) { + sourceProperties.values().removeIf(property -> property.isTransient(source)); + } targetProperties = createMapProperty(sourceProperties); } else { targetProperties = createProperty(target, true); @@ -440,12 +469,14 @@ private static String createCopierCode(Class source, Class target) { //复制到拓展对象 if (targetIsExtendable && !sourceIsExtendable && !sourceIsMap) { code.append("if(!ignore.contains(\"").append(sourceProperty.getName()).append("\")){\n\t"); + code.append(sourceProperty.generateVar("$$__value")).append("=$$__source.") + .append(sourceProperty.getReadMethod()).append(";\n"); if (!sourceProperty.isPrimitive()) { - code.append("if($$__source.").append(sourceProperty.getReadMethod()).append("!=null){\n"); + code.append("if($$__value!=null){\n"); } code.append("\t\t((org.hswebframework.ezorm.core.Extendable)$$__target).setExtension(") .append("\"").append(sourceProperty.name).append("\",") - .append("$$__source.").append(sourceProperty.getReadMethod()) + .append("$$__value") .append(");"); if (!sourceProperty.isPrimitive()) { code.append("\n\t}"); @@ -455,8 +486,10 @@ private static String createCopierCode(Class source, Class target) { continue; } code.append("if(!ignore.contains(\"").append(sourceProperty.getName()).append("\")){\n\t"); + code.append(sourceProperty.generateVar("$$__value")).append("=$$__source.") + .append(sourceProperty.getReadMethod()).append(";\n"); if (!sourceProperty.isPrimitive()) { - code.append("if($$__source.").append(sourceProperty.getReadMethod()).append("!=null){\n"); + code.append("if($$__value!=null){\n"); } code.append(targetProperty.generateVar(targetProperty.getName())).append("=") .append(sourceProperty.generateGetter(target, targetProperty.getType())) @@ -503,6 +536,13 @@ static abstract class ClassProperty { @Getter protected Class beanType; + protected boolean transientProperty; + + public boolean isTransient(Class sourceType) { + Field field = ReflectionUtils.findField(sourceType, name); + return transientProperty || field != null && Modifier.isTransient(field.getModifiers()); + } + public String getReadMethod() { return readMethodName + "()"; } @@ -518,7 +558,7 @@ public String getTypeName() { public String getTypeName(Class type) { String targetTypeName = type.getName(); if (type.isArray()) { - targetTypeName = type.getComponentType().getName() + "[]"; + targetTypeName = getTypeName(type.getComponentType()) + "[]"; } return targetTypeName; } @@ -558,7 +598,7 @@ protected String castWrapper(String getter) { public BiFunction, Class, String> createGetterFunction() { return (targetBeanType, targetType) -> { - String getterCode = "$$__source." + getReadMethod(); + String getterCode = "$$__value"; String generic = "org.hswebframework.web.bean.FastBeanCopier.EMPTY_CLASS_ARRAY"; Field field = ReflectionUtils.findField(targetBeanType, name); @@ -672,6 +712,7 @@ public String generateSetter(Class targetType, String getter) { static class BeanClassProperty extends ClassProperty { public BeanClassProperty(PropertyDescriptor descriptor) { type = descriptor.getPropertyType(); + transientProperty = Boolean.TRUE.equals(descriptor.getValue("transient")); readMethodName = descriptor.getReadMethod().getName(); writeMethodName = descriptor.getWriteMethod() == null ? null : descriptor.getWriteMethod().getName(); @@ -691,6 +732,8 @@ public BeanClassProperty(PropertyDescriptor descriptor) { static class RecordClassProperty extends ClassProperty { public RecordClassProperty(RecordComponent component) { type = component.getType(); + Transient annotation = component.getAccessor().getAnnotation(Transient.class); + transientProperty = annotation != null && annotation.value(); readMethodName = component.getAccessor().getName(); writeMethodName = null; diff --git a/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java new file mode 100644 index 000000000..6edb14820 --- /dev/null +++ b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java @@ -0,0 +1,105 @@ +package org.hswebframework.web.bean; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.Enumeration; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Supplier; +import java.util.stream.Stream; + +public class FastBeanCopierExceptionSpiTest { + + @Test + public void serviceLoaderCustomizesDetailAndKeepsFilteringLazy() throws Exception { + Path root = Files.createTempDirectory("exception-map-spi"); + String serviceName = "META-INF/services/" + ExceptionToMapConverter.class.getName(); + Path service = root.resolve(serviceName); + Files.createDirectories(service.getParent()); + Files.writeString(service, CustomConverter.class.getName()); + Thread thread = Thread.currentThread(); + ClassLoader original = thread.getContextClassLoader(); + String copierName = FastBeanCopier.class.getName(); + + try (URLClassLoader loader = new URLClassLoader(new URL[]{root.toUri().toURL()}, getClass().getClassLoader()) { + @Override + protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!name.equals(copierName) && !name.startsWith(copierName + "$")) { + return super.loadClass(name, resolve); + } + Class type = findLoadedClass(name); + if (type == null) { + try (InputStream input = getParent().getResourceAsStream(name.replace('.', '/') + ".class")) { + if (input == null) { + throw new ClassNotFoundException(name); + } + byte[] bytes = input.readAllBytes(); + type = defineClass(name, bytes, 0, bytes.length); + } catch (IOException e) { + throw new ClassNotFoundException(name, e); + } + } + if (resolve) { + resolveClass(type); + } + return type; + } + + @Override + public Enumeration getResources(String name) throws IOException { + return serviceName.equals(name) ? findResources(name) : super.getResources(name); + } + }) { + thread.setContextClassLoader(loader); + CustomConverter.detailReads = 0; + Class isolated = Class.forName(copierName, true, loader); + Method copy = isolated.getMethod("copy", Object.class, Object.class, String[].class); + Throwable error = new IllegalStateException("failed"); + + Map filtered = new LinkedHashMap<>(); + Assert.assertSame(filtered, copy.invoke(null, error, filtered, new String[]{"message", "detail"})); + Assert.assertEquals(Map.of("type", error.getClass().getName(), "extra", "custom"), filtered); + Assert.assertEquals(0, CustomConverter.detailReads); + + Map full = new LinkedHashMap<>(); + copy.invoke(null, error, full, new String[0]); + Assert.assertEquals("compact:failed", full.get("detail")); + Assert.assertEquals("custom", full.get("extra")); + Assert.assertEquals("failed", full.get("message")); + Assert.assertEquals(1, CustomConverter.detailReads); + } finally { + thread.setContextClassLoader(original); + try (Stream files = Files.walk(root)) { + for (Path file : files.sorted(Comparator.reverseOrder()).toList()) { + Files.delete(file); + } + } + } + } + + public static class CustomConverter extends DefaultExceptionToMapConverter { + static int detailReads; + + @Override + public void convert(Throwable source, BiConsumer> properties) { + super.convert(source, properties); + properties.accept("extra", () -> "custom"); + } + + @Override + protected String getDetail(Throwable source) { + detailReads++; + return "compact:" + source.getMessage(); + } + } +} diff --git a/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionTest.java b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionTest.java new file mode 100644 index 000000000..8142df112 --- /dev/null +++ b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionTest.java @@ -0,0 +1,143 @@ +package org.hswebframework.web.bean; + +import org.hswebframework.web.exception.BusinessException; +import org.hswebframework.web.i18n.LocaleUtils; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.context.support.StaticMessageSource; + +import java.io.PrintWriter; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +public class FastBeanCopierExceptionTest { + + @Test + public void exceptionAndErrorUseOnlyDescriptionFields() { + for (Throwable error : new Throwable[]{new IllegalStateException("failed"), new AssertionError("failed")}) { + error.initCause(new IllegalArgumentException("cause")); + error.addSuppressed(new IllegalStateException("suppressed")); + error.setStackTrace(new StackTraceElement[]{new StackTraceElement("example.Device", "read", "Device.java", 42)}); + + Map map = FastBeanCopier.copy(error, new LinkedHashMap<>()); + + Assert.assertEquals(Set.of("type", "message", "detail"), map.keySet()); + Assert.assertEquals(error.getClass().getName(), map.get("type")); + Assert.assertEquals("failed", map.get("message")); + String detail = (String) map.get("detail"); + Assert.assertTrue(detail.contains("example.Device.read(Device.java:42)")); + Assert.assertTrue(detail.contains("Caused by: java.lang.IllegalArgumentException: cause")); + Assert.assertTrue(detail.contains("Suppressed: java.lang.IllegalStateException: suppressed")); + } + } + + @Test + public void includeAndIgnoreSkipDetailGenerationAndArbitraryGetters() { + TrackingException error = new TrackingException("failed"); + + Assert.assertEquals(Map.of("type", error.getClass().getName(), "message", "failed"), + FastBeanCopier.copy(error, new LinkedHashMap<>(), "detail")); + Assert.assertEquals(1, error.messageReads); + Assert.assertEquals(0, error.detailReads); + + Assert.assertEquals(Map.of("type", error.getClass().getName()), + FastBeanCopier.copy(error, new LinkedHashMap<>(), FastBeanCopier.include("type"))); + Assert.assertEquals(1, error.messageReads); + Assert.assertEquals(0, error.detailReads); + } + + @Test + public void allPublicMapConversionEntrypointsShareExceptionMapping() { + Throwable error = new IllegalArgumentException("failed"); + Map expected = FastBeanCopier.copy(error, new LinkedHashMap<>()); + + Assert.assertEquals(expected, FastBeanCopier.copy(error, LinkedHashMap::new)); + Assert.assertEquals(expected, FastBeanCopier.copy(error, LinkedHashMap.class)); + Assert.assertEquals(expected, FastBeanCopier.DEFAULT_CONVERT.convert(error, Map.class, + FastBeanCopier.EMPTY_CLASS_ARRAY)); + } + + @Test + public void propertyLookupStillReadsOriginalExceptionProperties() { + Throwable error = new IllegalStateException("failed", new IllegalArgumentException("cause")); + + Assert.assertSame(error.getCause(), FastBeanCopier.getProperty(error, "cause")); + Assert.assertEquals("failed", FastBeanCopier.getProperty(error, "message")); + } + + @Test + public void nullMessageDoesNotOverwriteTarget() { + Map target = new LinkedHashMap<>(Map.of("message", "retained")); + + FastBeanCopier.copy(new IllegalStateException(), target, "detail"); + + Assert.assertEquals("retained", target.get("message")); + Assert.assertEquals(IllegalStateException.class.getName(), target.get("type")); + } + + @Test + public void i18nReasonBusinessCodeAndTypedArgumentsStayDistinct() { + StaticMessageSource messages = new StaticMessageSource(); + messages.addMessage("test.reason", Locale.ENGLISH, "Rejected {0,number,integer}"); + messages.addMessage("test.reason", Locale.CHINESE, "拒绝 {0,number,integer}"); + BusinessException error = new BusinessException("test.reason", "BUSINESS_REJECTED", 409, 12) { + @Override + public String getLocalizedMessage(Locale locale) { + return messages.getMessage(getI18nCode(), getArgs(), getOriginalMessage(), locale); + } + }; + + Map map = LocaleUtils.doWith(Locale.ENGLISH, + () -> FastBeanCopier.copy(error, new LinkedHashMap<>(), "detail")); + + Assert.assertEquals("Rejected 12", map.get("message")); + Assert.assertEquals("test.reason", map.get("i18nCode")); + Assert.assertEquals("BUSINESS_REJECTED", map.get("code")); + Assert.assertEquals(409, map.get("status")); + Assert.assertArrayEquals(new Object[]{12}, (Object[]) map.get("args")); + Assert.assertEquals("拒绝 12", messages.getMessage((String) map.get("i18nCode"), + (Object[]) map.get("args"), Locale.CHINESE)); + } + + @Test + public void customValueConverterIsAppliedAndNullConversionSkipsWriting() { + Converter converter = new Converter() { + @Override + public T convert(Object source, Class targetClass, Class[] genericType) { + return source.equals("failed") ? null : FastBeanCopier.DEFAULT_CONVERT.convert(source, targetClass, genericType); + } + }; + Map target = new LinkedHashMap<>(Map.of("message", "retained")); + + FastBeanCopier.copy(new IllegalStateException("failed"), target, converter, "detail"); + + Assert.assertEquals(Map.of("type", IllegalStateException.class.getName(), "message", "retained"), target); + } + + public static class TrackingException extends RuntimeException { + int messageReads; + int detailReads; + + public TrackingException(String message) { + super(message); + } + + @Override + public String getMessage() { + messageReads++; + return super.getMessage(); + } + + @Override + public void printStackTrace(PrintWriter writer) { + detailReads++; + super.printStackTrace(writer); + } + + public Object getRuntimeResource() { + throw new AssertionError("Arbitrary exception getter must not be called"); + } + } +} diff --git a/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierReadOnceTest.java b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierReadOnceTest.java new file mode 100644 index 000000000..9adfdd7a7 --- /dev/null +++ b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierReadOnceTest.java @@ -0,0 +1,183 @@ +package org.hswebframework.web.bean; + +import org.hswebframework.ezorm.core.DefaultExtendable; +import org.junit.Assert; +import org.junit.Test; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class FastBeanCopierReadOnceTest { + + @Test + public void changingGetterIsReadOnceForMapBeanRecordAndExtension() { + ChangingSource source = new ChangingSource(); + Assert.assertEquals(Map.of("name", "first"), FastBeanCopier.copy(source, new LinkedHashMap<>())); + Assert.assertEquals(1, source.reads); + + source = new ChangingSource(); + Assert.assertEquals("first", FastBeanCopier.copy(source, new NameTarget()).getName()); + Assert.assertEquals(1, source.reads); + + source = new ChangingSource(); + Assert.assertEquals(new NameRecord("first"), FastBeanCopier.copy(source, NameRecord.class)); + Assert.assertEquals(1, source.reads); + + source = new ChangingSource(); + Assert.assertEquals("first", FastBeanCopier.copy(source, new DefaultExtendable()).getExtension("name")); + Assert.assertEquals(1, source.reads); + } + + @Test + public void nullSourceValueIsReadOnceAndDoesNotOverwriteTarget() { + NullSource source = new NullSource(); + Map target = new LinkedHashMap<>(Map.of("name", "retained")); + + Assert.assertEquals(Map.of("name", "retained"), FastBeanCopier.copy(source, target)); + Assert.assertEquals(1, source.reads); + } + + @Test + public void mapValueIsReadOnceForWritableBean() { + ChangingMap source = new ChangingMap(); + + Assert.assertEquals("first", FastBeanCopier.copy(source, new NameTarget()).getName()); + Assert.assertEquals(1, source.reads); + } + + @Test + public void excludedGettersAreNotInvoked() { + BrokenSource source = new BrokenSource(); + + Assert.assertEquals(Map.of("name", "ok"), + FastBeanCopier.copy(source, new LinkedHashMap<>(), "debug")); + Assert.assertEquals(Map.of("name", "ok"), + FastBeanCopier.copy(source, new LinkedHashMap<>(), FastBeanCopier.include("name"))); + } + + @Test + public void getterErrorIsPropagatedWithoutWrapping() { + BrokenSource source = new BrokenSource(); + + AssertionError thrown = Assert.assertThrows(AssertionError.class, + () -> FastBeanCopier.copy(source, new LinkedHashMap<>())); + Assert.assertSame(source.error, thrown); + } + + @Test + public void nestedErrorIsReadOnceAndRetainsIdentity() { + ErrorSource source = new ErrorSource(); + + Map copied = FastBeanCopier.copy(source, new LinkedHashMap<>()); + + Assert.assertSame(source.error, copied.get("error")); + Assert.assertEquals(1, source.reads); + } + + @Test + public void sourceValuesWithOpaqueTypesAndMultidimensionalArraysStayShallow() { + OpaqueSource source = new OpaqueSource(); + + Map copied = FastBeanCopier.copy(source, new LinkedHashMap<>()); + + Assert.assertSame(source.value, copied.get("value")); + Assert.assertSame(source.matrix, copied.get("matrix")); + } + + @Test + public void throwableMapUsesTextDetailForCyclicCause() { + Error error = new AssertionError("outer"); + Exception cause = new IllegalStateException("cause"); + error.initCause(cause); + cause.initCause(error); + + Map copied = FastBeanCopier.copy(error, new LinkedHashMap<>()); + + Assert.assertEquals("outer", copied.get("message")); + Assert.assertEquals(error.getClass().getName(), copied.get("type")); + Assert.assertTrue(((String) copied.get("detail")).contains("CIRCULAR REFERENCE")); + Assert.assertFalse(copied.containsKey("cause")); + Assert.assertFalse(copied.containsKey("stackTrace")); + Assert.assertFalse(copied.containsKey("suppressed")); + } + + public static class ChangingSource { + int reads; + + public String getName() { + return ++reads == 1 ? "first" : null; + } + } + + public static class NullSource { + int reads; + + public String getName() { + reads++; + return null; + } + } + + public static class NameTarget { + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + public record NameRecord(String name) { + } + + public static class ChangingMap extends LinkedHashMap { + int reads; + + @Override + public Object get(Object key) { + return ++reads == 1 ? "first" : null; + } + } + + public static class BrokenSource { + final AssertionError error = new AssertionError("getter failed"); + + public String getName() { + return "ok"; + } + + public String getDebug() { + throw error; + } + } + + public static class ErrorSource { + final Error error = new AssertionError("nested"); + int reads; + + public Error getError() { + reads++; + return error; + } + } + + private enum HiddenValue { + VALUE + } + + public static class OpaqueSource { + final HiddenValue value = HiddenValue.VALUE; + final int[][] matrix = {{1, 2}}; + + public HiddenValue getValue() { + return value; + } + + public int[][] getMatrix() { + return matrix; + } + } +} diff --git a/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierTransientTest.java b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierTransientTest.java new file mode 100644 index 000000000..5272cb4a9 --- /dev/null +++ b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierTransientTest.java @@ -0,0 +1,135 @@ +package org.hswebframework.web.bean; + +import org.junit.Assert; +import org.junit.Test; + +import java.beans.Transient; +import java.util.LinkedHashMap; +import java.util.Map; + +public class FastBeanCopierTransientTest { + + @Test + public void mapExportSkipsTransientFieldsAndBeanPropertiesBeforeReading() { + ExportSource source = new ExportSource(); + + Assert.assertEquals(Map.of("name", "exported", "visible", "kept"), + FastBeanCopier.copy(source, new LinkedHashMap<>())); + Assert.assertEquals(0, source.inheritedReads); + Assert.assertEquals(0, source.errorReads); + } + + @Test + public void includeCannotExportTransientProperties() { + ExportSource source = new ExportSource(); + + Assert.assertTrue(FastBeanCopier.copy(source, new LinkedHashMap<>(), + FastBeanCopier.include("error", "inherited", "diagnostic", "setterMarked")).isEmpty()); + Assert.assertEquals(0, source.inheritedReads); + Assert.assertEquals(0, source.errorReads); + } + + @Test + public void defaultConverterUsesTheSameMapExportRules() { + Map map = FastBeanCopier.DEFAULT_CONVERT.convert(new ExportSource(), Map.class, + FastBeanCopier.EMPTY_CLASS_ARRAY); + + Assert.assertEquals(Map.of("name", "exported", "visible", "kept"), map); + } + + @Test + public void beanAndRecordCopyRetainTransientValues() { + TransferBean source = new TransferBean(); + source.setToken("local"); + + Assert.assertEquals("local", FastBeanCopier.copy(source, new TransferBean()).getToken()); + Assert.assertEquals(new TokenRecord("local"), FastBeanCopier.copy(source, TokenRecord.class)); + Assert.assertEquals("local", + FastBeanCopier.copy(Map.of("token", "local"), new TransferBean()).getToken()); + Assert.assertEquals("local", FastBeanCopier.getProperty(source, "token")); + } + + @Test + public void recordExportHonorsTransientAccessor() { + Assert.assertEquals(Map.of("name", "record"), + FastBeanCopier.copy(new ExportRecord("record", "local"), new LinkedHashMap<>())); + } + + @Test + public void mapKeysAreNotFilteredByPropertyNames() { + Map source = Map.of("error", "value", "token", "value"); + + Assert.assertEquals(source, FastBeanCopier.copy(source, new LinkedHashMap<>())); + } + + @Test + public void transientFalseCannotOverrideTransientField() { + Assert.assertTrue(FastBeanCopier.copy(new TransferBean(), new LinkedHashMap<>()).isEmpty()); + } + + public static class ExportBase { + private transient String inherited = "local"; + int inheritedReads; + + public String getInherited() { + inheritedReads++; + return inherited; + } + } + + public static class ExportSource extends ExportBase { + private transient Throwable error; + int errorReads; + + public String getName() { + return "exported"; + } + + public Throwable getError() { + errorReads++; + throw new AssertionError("Transient error getter must not run"); + } + + @Transient + public String getDiagnostic() { + throw new AssertionError("Transient property getter must not run"); + } + + public String getSetterMarked() { + throw new AssertionError("Setter-marked property getter must not run"); + } + + @Transient + public void setSetterMarked(String value) { + } + + @Transient(false) + public String getVisible() { + return "kept"; + } + } + + public static class TransferBean { + private transient String token = "local"; + + @Transient(false) + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + } + + public record TokenRecord(String token) { + } + + public record ExportRecord(String name, String diagnostic) { + @Transient + @Override + public String diagnostic() { + throw new AssertionError("Transient record accessor must not run"); + } + } +} From ff5c3fcbcec3567754d7a0caea3f5f803d8cb518 Mon Sep 17 00:00:00 2001 From: zhou-hao Date: Fri, 27 Nov 2026 16:49:20 +0800 Subject: [PATCH 2/5] =?UTF-8?q?fix(bean):=20=E8=BF=98=E5=8E=9F=20Map=20?= =?UTF-8?q?=E4=B8=AD=E7=9A=84=E5=BC=82=E5=B8=B8=E5=B9=B6=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E5=BC=82=E5=B8=B8=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 已兼容的 Throwable 保留原引用,异常描述通过双向 SPI 受控还原。 平台国际化异常恢复为对应 NoStackTrace 实现,未知类型使用安全包装, 保留远端类型、诊断、消息回退、参数及校验详情,不按类型名加载类。 统一普通 Bean、record、类目标和已有异常目标的转换路径,校验目标 可赋值性及描述字段。将本 PR 未发布的 SPI 收敛为 ExceptionConverter。 --- hsweb-core/README.md | 10 +- .../web/bean/DefaultExceptionConverter.java | 169 +++++++++ .../bean/DefaultExceptionToMapConverter.java | 40 --- .../web/bean/ExceptionConverter.java | 25 ++ .../web/bean/ExceptionToMapConverter.java | 18 - .../web/bean/FastBeanCopier.java | 41 ++- .../web/exception/RemoteException.java | 70 ++++ .../exception/RemoteExceptionMetadata.java | 43 +++ .../FastBeanCopierExceptionRestoreTest.java | 332 ++++++++++++++++++ .../bean/FastBeanCopierExceptionSpiTest.java | 49 ++- .../web/i18n/RemoteExceptionI18nTest.java | 113 ++++++ 11 files changed, 840 insertions(+), 70 deletions(-) create mode 100644 hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionConverter.java delete mode 100644 hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionToMapConverter.java create mode 100644 hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionConverter.java delete mode 100644 hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionToMapConverter.java create mode 100644 hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteException.java create mode 100644 hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteExceptionMetadata.java create mode 100644 hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionRestoreTest.java create mode 100644 hsweb-core/src/test/java/org/hswebframework/web/i18n/RemoteExceptionI18nTest.java diff --git a/hsweb-core/README.md b/hsweb-core/README.md index 8b75de977..9d2a225ac 100644 --- a/hsweb-core/README.md +++ b/hsweb-core/README.md @@ -33,9 +33,15 @@ Bean/record 转 Map 时排除 `transient` 字段(包含继承字段)及 Java 直接将 Throwable 转 Map(包括 `DEFAULT_CONVERT.convert(error, Map.class, ...)`)使用固定描述字段:`type` 为完整类名,`message` 为异常消息,`detail` 为含 cause/suppressed 的完整堆栈文本;`I18nSupportException` 另提供 `i18nCode`、`args`,`BusinessException` 另提供业务 `code`、`status`。参数保持浅复制及原类型;空值跳过,不再枚举异常的其他 getter 或携带原始 cause/suppressed/stackTrace 对象。include/ignore 在取值前应用,排除 detail 时不生成堆栈,值转换仍使用调用方的 Converter。Map 用于错误描述,异常的真实类型还原不依赖类名反射实例化。 -可在 `META-INF/services/org.hswebframework.web.bean.ExceptionToMapConverter` 注册自定义异常映射实现。首次异常转换时使用线程上下文 ClassLoader 发现的首个实现,每个运行环境应只注册一个;无实现时回退 `DefaultExceptionToMapConverter`。实例按 copier 的 ClassLoader 复用,自定义实现应无状态或线程安全。SPI 按字段提供延迟 Supplier,由 copier 统一过滤、读取及转换;继承默认实现并覆盖 `getDetail(Throwable)` 可复用上层平台的栈精简逻辑,自定义栈处理需保留循环引用处理,无需改变其他字段或引入反向依赖。 +目标声明为 Throwable 体系时,兼容的现成异常直接保留原引用;异常描述 Map 通过 `ExceptionConverter.fromMap` 受控恢复。默认实现要求非空字符串 type;识别 hsweb-core 中 I18nSupportException、BusinessException、NotFoundException、ValidationException 及其 NoStackTrace 类名,恢复为相应 NoStackTrace 实现。未知类型使用 `RemoteException`(BusinessException.NoStackTrace 子类)安全包装;通过 `RemoteExceptionMetadata` 保留远端 type/detail、发送端 message、国际化及业务字段,不按 type 任意加载类或解析 detail。恢复结果必须可赋值给目标声明;其余具体异常或 Error 声明需由 SPI 提供对应结果,否则明确报错。Object/Map 目标不因存在 type 字段而主动恢复。 -访问器回归由 `FastBeanCopierBeanTest`、`FastBeanCopierReadOnlyTest`、`FastBeanCopierReadOnceTest`、`FastBeanCopierTransientTest` 和 `FastBeanCopierTest` 覆盖,包括只读源属性、单次取值、导出排除规则、目标可写边界、不同访问器风格、继承泛型、忽略属性、record、全局配置隔离及静态访问器排除。`FastBeanCopierExceptionTest` 与 `FastBeanCopierExceptionSpiTest` 覆盖异常描述、循环 cause、国际化字段、值转换和 SPI 发现及延迟取值。 +ValidationException 的 details 以 property/message/detail 字段 Map 列表导出,恢复时保留字段错误及详情;details 中的业务值保持浅复制。已知异常固定的业务 code/status 若与描述冲突会明确拒绝,不静默丢失。鉴权等上层模块的异常由其 SPI 实现扩展,hsweb-core 不反向依赖这些模块。 + +还原支持本地 Object[] 与 JSON List 形式的 args,复制参数容器并保留参数值类型;status 必须是 int 范围内的整数。接收端无对应译文时使用发送端 message 回退。恢复后的异常再次转 Map 时沿用原远端 type/detail,不生成本地替代栈;缺省字段保持缺省。`copy(map, Throwable.class)` 与 `copy(map, existingThrowable)` 采用同一恢复路径,后者返回新异常,调用方必须使用返回值;复制到普通 Bean/record 的异常字段也使用该转换规则。 + +可在 `META-INF/services/org.hswebframework.web.bean.ExceptionConverter` 注册自定义双向实现(`toMap` / `fromMap`)。首次异常转换时使用线程上下文 ClassLoader 发现的首个实现,每个运行环境应只注册一个;无实现时回退 `DefaultExceptionConverter`。实例按 copier 的 ClassLoader 复用,自定义实现应无状态或线程安全。toMap 按字段提供延迟 Supplier,由 copier 统一过滤、读取及转换;继承默认实现并覆盖 `getDetail(Throwable)` 可精简原始异常的栈,自定义栈处理需保留循环引用处理。携带 RemoteExceptionMetadata 的异常直接沿用远端 detail,不再调用此栈渲染方法。fromMap 应返回与目标声明兼容的异常,copier 拒绝 null 或不兼容的 SPI 返回值。 + +访问器回归由 `FastBeanCopierBeanTest`、`FastBeanCopierReadOnlyTest`、`FastBeanCopierReadOnceTest`、`FastBeanCopierTransientTest` 和 `FastBeanCopierTest` 覆盖,包括只读源属性、单次取值、导出排除规则、目标可写边界、不同访问器风格、继承泛型、忽略属性、record、全局配置隔离及静态访问器排除。`FastBeanCopierExceptionTest`、`FastBeanCopierExceptionRestoreTest`、`FastBeanCopierExceptionSpiTest` 及 `RemoteExceptionI18nTest` 覆盖异常描述、循环 cause、受控还原、JSON 往返、国际化回退和重译、值转换及双向 SPI 发现。 约定: 如果属性类实现了`Cloneable`接口,在复制的时候将调用`clone`方法.所以如果你实现了`Cloneable`接口,就必须重写`clone`方法并且为`public`修饰的. diff --git a/hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionConverter.java b/hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionConverter.java new file mode 100644 index 000000000..21487569c --- /dev/null +++ b/hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionConverter.java @@ -0,0 +1,169 @@ +package org.hswebframework.web.bean; + +import org.hswebframework.web.exception.BusinessException; +import org.hswebframework.web.exception.I18nSupportException; +import org.hswebframework.web.exception.NotFoundException; +import org.hswebframework.web.exception.RemoteException; +import org.hswebframework.web.exception.RemoteExceptionMetadata; +import org.hswebframework.web.exception.RemoteExceptionMetadata.Description; +import org.hswebframework.web.exception.ValidationException; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +/** + * 异常描述与受控还原,不对异常的任意 getter 进行内省,也不按远端 type 加载类。 + * 已知平台异常还原为对应 NoStackTrace,未知类型使用携带远端描述的安全包装。 + */ +public class DefaultExceptionConverter implements ExceptionConverter { + + @Override + public void toMap(Throwable source, BiConsumer> properties) { + properties.accept("type", () -> source instanceof RemoteExceptionMetadata remote + ? remote.getRemoteType() : source.getClass().getName()); + properties.accept("message", source::getMessage); + properties.accept("detail", () -> source instanceof RemoteExceptionMetadata remote + ? remote.getRemoteDetail() : getDetail(source)); + if (source instanceof RemoteExceptionMetadata remote) { + properties.accept("i18nCode", () -> remote.getRemoteDescription().i18nCode()); + properties.accept("args", () -> remote.getRemoteDescription().args()); + properties.accept("code", () -> remote.getRemoteDescription().code()); + properties.accept("status", () -> remote.getRemoteDescription().status()); + properties.accept("details", () -> describeDetails(source instanceof ValidationException validation + ? validation.getDetails() : remote.getRemoteDescription().details())); + return; + } + if (source instanceof I18nSupportException i18n) { + properties.accept("i18nCode", i18n::getI18nCode); + properties.accept("args", i18n::getArgs); + } + if (source instanceof BusinessException business) { + properties.accept("code", business::getCode); + properties.accept("status", business::getStatus); + } + if (source instanceof ValidationException validation) { + properties.accept("details", () -> describeDetails(validation.getDetails())); + } + } + + @Override + public Throwable fromMap(Map source, Class targetType) { + Description description = new Description( + stringValue(source, "type"), stringValue(source, "message"), stringValue(source, "detail"), + stringValue(source, "i18nCode"), arguments(source.get("args")), stringValue(source, "code"), + status(source.get("status")), details(source.get("details"))); + String type = description.type(); + Throwable restored; + if (isType(type, NotFoundException.class, NotFoundException.NoStackTrace.class)) { + restored = new RemoteException.NotFound(description); + } else if (isType(type, ValidationException.class, ValidationException.NoStackTrace.class)) { + restored = new RemoteException.Validation(description); + } else if (isType(type, I18nSupportException.class, I18nSupportException.NoStackTrace.class)) { + restored = new RemoteException.I18n(description); + } else { + // BusinessException 的 NoStackTrace 同时作为未知类型的安全包装。 + restored = new RemoteException(description); + } + if (restored instanceof BusinessException business + && (!Objects.equals(description.code(), business.getCode()) + || description.status() != null && description.status() != business.getStatus())) { + throw new IllegalArgumentException("Exception business fields do not match type: " + type); + } + if (!targetType.isInstance(restored)) { + throw new UnsupportedOperationException("Unsupported exception target: " + targetType.getName()); + } + return restored; + } + + private boolean isType(String type, Class normal, Class stackless) { + return normal.getName().equals(type) || stackless.getName().equals(type); + } + + private String stringValue(Map source, String name) { + Object value = source.get(name); + if (value == null || value instanceof String) { + return (String) value; + } + throw new IllegalArgumentException("Exception field must be a string: " + name); + } + + private Object[] arguments(Object value) { + if (value == null) { + return null; + } + if (value instanceof Object[] args) { + return args.clone(); + } + if (value instanceof List args) { + return args.toArray(); + } + throw new IllegalArgumentException("Exception args must be an array or list"); + } + + private Integer status(Object value) { + if (value == null) { + return null; + } + if (value instanceof Number) { + try { + return new BigDecimal(value.toString()).intValueExact(); + } catch (ArithmeticException | NumberFormatException e) { + throw new IllegalArgumentException("Exception status must be an int", e); + } + } + throw new IllegalArgumentException("Exception status must be an int"); + } + + private List> describeDetails(List details) { + if (details == null) { + return null; + } + List> result = new ArrayList<>(details.size()); + for (ValidationException.Detail detail : details) { + Map fields = new LinkedHashMap<>(); + fields.put("property", detail.getProperty()); + fields.put("message", detail.getMessage()); + fields.put("detail", detail.getDetail()); + result.add(fields); + } + return result; + } + + private List details(Object value) { + if (value == null) { + return null; + } + if (!(value instanceof List list)) { + throw new IllegalArgumentException("Exception details must be a list"); + } + List result = new ArrayList<>(list.size()); + for (Object item : list) { + if (item instanceof ValidationException.Detail detail) { + result.add(new ValidationException.Detail(detail.getProperty(), detail.getMessage(), detail.getDetail())); + } else if (item instanceof Map fields) { + result.add(new ValidationException.Detail( + stringValue(fields, "property"), stringValue(fields, "message"), fields.get("detail"))); + } else { + throw new IllegalArgumentException("Exception detail must be an object"); + } + } + return result; + } + + /** + * 为原始异常生成诊断,可覆盖以使用上层平台的栈精简能力;远端描述直接沿用。 + */ + protected String getDetail(Throwable source) { + StringWriter writer = new StringWriter(); + source.printStackTrace(new PrintWriter(writer)); + return writer.toString(); + } +} diff --git a/hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionToMapConverter.java b/hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionToMapConverter.java deleted file mode 100644 index 9ea65685e..000000000 --- a/hsweb-core/src/main/java/org/hswebframework/web/bean/DefaultExceptionToMapConverter.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.hswebframework.web.bean; - -import org.hswebframework.web.exception.BusinessException; -import org.hswebframework.web.exception.I18nSupportException; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.function.BiConsumer; -import java.util.function.Supplier; - -/** - * 提供异常描述及国际化信息,不对异常的任意 getter 进行内省。 - * detail 使用完整堆栈文本,避免在 Map 中保留 cause/suppressed 对象图。 - */ -public class DefaultExceptionToMapConverter implements ExceptionToMapConverter { - - @Override - public void convert(Throwable source, BiConsumer> properties) { - properties.accept("type", () -> source.getClass().getName()); - properties.accept("message", source::getMessage); - properties.accept("detail", () -> getDetail(source)); - if (source instanceof I18nSupportException i18n) { - properties.accept("i18nCode", i18n::getI18nCode); - properties.accept("args", i18n::getArgs); - } - if (source instanceof BusinessException business) { - properties.accept("code", business::getCode); - properties.accept("status", business::getStatus); - } - } - - /** - * 覆盖此方法可使用上层平台的栈精简能力。 - */ - protected String getDetail(Throwable source) { - StringWriter writer = new StringWriter(); - source.printStackTrace(new PrintWriter(writer)); - return writer.toString(); - } -} diff --git a/hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionConverter.java b/hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionConverter.java new file mode 100644 index 000000000..c4c65baf1 --- /dev/null +++ b/hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionConverter.java @@ -0,0 +1,25 @@ +package org.hswebframework.web.bean; + +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +/** + * 异常与 Map 的双向转换,通过 {@link java.util.ServiceLoader} 注册。 + * + *

字段值必须延迟到 Supplier 被调用时读取,使 copier 能在读取前应用 include/ignore。 + * copier 负责空值跳过和值转换;提供者不应提前生成堆栈等诊断信息。 + * 自定义实现可继承 {@link DefaultExceptionConverter}。 + * + * @see FastBeanCopier + */ +public interface ExceptionConverter { + + void toMap(Throwable source, BiConsumer> properties); + + /** + * 从异常描述恢复可赋值给目标声明的异常,不按远端 type 任意加载类。 + * 不支持的目标或无效描述应明确抛错,不能返回 null 或不兼容的异常。 + */ + Throwable fromMap(Map source, Class targetType); +} diff --git a/hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionToMapConverter.java b/hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionToMapConverter.java deleted file mode 100644 index f799a9acc..000000000 --- a/hsweb-core/src/main/java/org/hswebframework/web/bean/ExceptionToMapConverter.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.hswebframework.web.bean; - -import java.util.function.BiConsumer; -import java.util.function.Supplier; - -/** - * 异常转 Map 的字段提供者,通过 {@link java.util.ServiceLoader} 注册。 - * - *

字段值必须延迟到 Supplier 被调用时读取,使 copier 能在读取前应用 include/ignore。 - * copier 负责空值跳过和值转换;提供者不应提前生成堆栈等诊断信息。 - * 自定义实现可继承 {@link DefaultExceptionToMapConverter}。 - * - * @see FastBeanCopier - */ -public interface ExceptionToMapConverter { - - void convert(Throwable source, BiConsumer> properties); -} diff --git a/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java b/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java index 541f45eef..6f90bd353 100644 --- a/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java +++ b/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java @@ -1,7 +1,6 @@ package org.hswebframework.web.bean; import com.google.common.collect.Maps; -import io.netty.util.internal.ConcurrentSet; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.SneakyThrows; @@ -30,7 +29,6 @@ import java.lang.reflect.RecordComponent; import java.util.*; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; @@ -150,6 +148,11 @@ public static T copy(S source, Supplier target, String... ignore) { @SneakyThrows public static T copy(S source, Class target, String... ignore) { + if (Throwable.class.isAssignableFrom(target)) { + Set ignored = ignore == null || ignore.length == 0 + ? Collections.emptySet() : new HashSet<>(Arrays.asList(ignore)); + return copyToThrowable(source, target, DEFAULT_CONVERT, ignored); + } if (target.isRecord()) { return copyToRecord(source, target, DEFAULT_CONVERT, ignore); } @@ -166,12 +169,16 @@ public static T copy(S source, T target, Set ignore) { @SuppressWarnings("all") public static T copy(S source, T target, Converter converter, Set ignore) { + if (target instanceof Throwable) { + // 异常的消息等属性不能通过 setter 修改,返回转换后的异常。 + return (T) copyToThrowable(source, getUserClass(target), converter, ignore); + } if (target != null && getUserClass(target).isRecord()) { // record 不可变,无法写入已存在实例;这里按组件名重新构造并返回新实例。 return (T) copyToRecord(source, (Class) getUserClass(target), converter, ignore); } if (source instanceof Throwable && target instanceof Map) { - ExceptionConverterHolder.INSTANCE.convert((Throwable) source, (name, supplier) -> { + ExceptionConverterHolder.INSTANCE.toMap((Throwable) source, (name, supplier) -> { if (!ignore.contains(name)) { Object value = supplier.get(); if (value != null) { @@ -203,11 +210,18 @@ public static T copy(S source, T target, Converter converter, Set return target; } + private static T copyToThrowable(Object source, Class target, Converter converter, Set ignore) { + if (source instanceof Map && !CollectionUtils.isEmpty(ignore)) { + source = Maps.filterKeys((Map) source, name -> !ignore.contains(name)); + } + return converter.convert(source, target, EMPTY_CLASS_ARRAY); + } + private static class ExceptionConverterHolder { - private static final ExceptionToMapConverter INSTANCE = ServiceLoader - .load(ExceptionToMapConverter.class) + private static final ExceptionConverter INSTANCE = ServiceLoader + .load(ExceptionConverter.class) .findFirst() - .orElseGet(DefaultExceptionToMapConverter::new); + .orElseGet(DefaultExceptionConverter::new); } static T copyToRecord(S source, Class target, Converter converter, String... ignore) { @@ -875,6 +889,21 @@ public T convert(Object source, Class targetClass, Class[] genericType) { if (source == null) { return null; } + if (Throwable.class.isAssignableFrom(targetClass)) { + if (targetClass.isInstance(source)) { + return (T) source; + } + if (!(source instanceof Map)) { + throw new IllegalArgumentException("Cannot convert value to exception: " + targetClass.getName()); + } + Throwable restored = ExceptionConverterHolder.INSTANCE.fromMap( + (Map) source, (Class) targetClass); + if (!targetClass.isInstance(restored)) { + throw new UnsupportedOperationException("Exception converter returned an incompatible value for " + + targetClass.getName()); + } + return (T) restored; + } ClassDescription target = ClassDescriptions.getDescription(targetClass); if (target.isEnumType()) { diff --git a/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteException.java b/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteException.java new file mode 100644 index 000000000..b05c141a6 --- /dev/null +++ b/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteException.java @@ -0,0 +1,70 @@ +package org.hswebframework.web.exception; + +import lombok.Getter; + +/** + * 未知远端异常的安全包装,不加载远端类或解析堆栈。 + * 已知平台异常使用对应的 NoStackTrace 实现,并携带相同的远端描述。 + */ +@Getter +public class RemoteException extends BusinessException.NoStackTrace implements RemoteExceptionMetadata { + private static final long serialVersionUID = 1L; + + private final Description remoteDescription; + + public RemoteException(Description description) { + super(description.i18nCode(), description.code(), + description.status() == null ? 500 : description.status(), description.arguments()); + remoteDescription = description; + } + + @Override + public String getOriginalMessage() { + return remoteDescription.message(); + } + + @Getter + public static final class I18n extends I18nSupportException.NoStackTrace implements RemoteExceptionMetadata { + private final Description remoteDescription; + + public I18n(Description description) { + super(description.i18nCode(), description.arguments()); + remoteDescription = description; + } + + @Override + public String getOriginalMessage() { + return remoteDescription.message(); + } + } + + @Getter + public static final class NotFound extends NotFoundException.NoStackTrace implements RemoteExceptionMetadata { + private final Description remoteDescription; + + public NotFound(Description description) { + super(description.i18nCode(), description.arguments()); + remoteDescription = description; + } + + @Override + public String getOriginalMessage() { + return remoteDescription.message(); + } + } + + @Getter + public static final class Validation extends ValidationException.NoStackTrace implements RemoteExceptionMetadata { + private final Description remoteDescription; + + public Validation(Description description) { + super(description.i18nCode(), description.details(), description.arguments()); + remoteDescription = description; + } + + @Override + public String getOriginalMessage() { + return remoteDescription.message(); + } + } +} diff --git a/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteExceptionMetadata.java b/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteExceptionMetadata.java new file mode 100644 index 000000000..079fc2319 --- /dev/null +++ b/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteExceptionMetadata.java @@ -0,0 +1,43 @@ +package org.hswebframework.web.exception; + +import org.springframework.util.Assert; + +import java.io.Serializable; +import java.util.List; + +/** + * 恢复后的异常携带的远端描述。再次转 Map 时保留远端类型和诊断信息。 + */ +public interface RemoteExceptionMetadata { + + Description getRemoteDescription(); + + default String getRemoteType() { + return getRemoteDescription().type(); + } + + default String getRemoteDetail() { + return getRemoteDescription().detail(); + } + + default Integer getRemoteStatus() { + return getRemoteDescription().status(); + } + + record Description(String type, + String message, + String detail, + String i18nCode, + Object[] args, + String code, + Integer status, + List details) implements Serializable { + public Description { + Assert.hasText(type, "Remote exception type is required"); + } + + public Object[] arguments() { + return args == null ? new Object[0] : args; + } + } +} diff --git a/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionRestoreTest.java b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionRestoreTest.java new file mode 100644 index 000000000..3f81c0f64 --- /dev/null +++ b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionRestoreTest.java @@ -0,0 +1,332 @@ +package org.hswebframework.web.bean; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.hswebframework.web.exception.BusinessException; +import org.hswebframework.web.exception.I18nSupportException; +import org.hswebframework.web.exception.NotFoundException; +import org.hswebframework.web.exception.RemoteException; +import org.hswebframework.web.exception.RemoteExceptionMetadata; +import org.hswebframework.web.exception.ValidationException; +import org.junit.Assert; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.math.BigDecimal; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class FastBeanCopierExceptionRestoreTest { + + @Test + public void liveExceptionsRetainIdentityInBeansRecordsAndDirectConversion() { + BusinessException original = new BusinessException("reason", "BUSINESS", 409, 12); + original.initCause(new IllegalStateException("cause")); + original.addSuppressed(new IllegalArgumentException("suppressed")); + + ThrowableHolder holder = FastBeanCopier.copy(Map.of("error", original), new ThrowableHolder()); + Assert.assertSame(original, holder.getError()); + Assert.assertSame(original.getCause(), holder.getError().getCause()); + Assert.assertSame(original, FastBeanCopier.copy(Map.of("error", original), new BusinessHolder()).getError()); + Assert.assertSame(original, FastBeanCopier.copy(Map.of("error", original), ErrorRecord.class).error()); + Assert.assertSame(original, FastBeanCopier.copy(original, Throwable.class)); + Assert.assertSame(original, FastBeanCopier.copy(original, new Throwable())); + Assert.assertSame(original, FastBeanCopier.DEFAULT_CONVERT.convert(original, Throwable.class, + FastBeanCopier.EMPTY_CLASS_ARRAY)); + Assert.assertSame(original, FastBeanCopier.copy(Map.of("errors", List.of(original)), new ErrorList()).getErrors().get(0)); + Error error = new AssertionError("local error"); + Assert.assertSame(error, FastBeanCopier.copy(Map.of("error", error), new ThrowableHolder()).getError()); + } + + @Test + public void descriptionRestoresMessageAndRemoteMetadataForAllSupportedTargets() { + Map description = description(); + for (Class target : List.of(Throwable.class, Exception.class, RuntimeException.class, + I18nSupportException.class, BusinessException.class, BusinessException.NoStackTrace.class, RemoteException.class)) { + Throwable restored = FastBeanCopier.copy(description, target); + Assert.assertTrue(target.isInstance(restored)); + RemoteException remote = (RemoteException) restored; + Assert.assertEquals("failed", remote.getMessage()); + Assert.assertEquals("remote.Problem", remote.getRemoteType()); + Assert.assertEquals("remote stack", remote.getRemoteDetail()); + Assert.assertEquals(0, remote.getStackTrace().length); + Assert.assertEquals(description, FastBeanCopier.copy(remote, new LinkedHashMap<>())); + } + } + + @Test + public void platformFamiliesRestoreTheirNoStackTraceImplementations() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + List details = List.of(new ValidationException.Detail("field", "invalid", "extra")); + for (I18nSupportException original : List.of( + new I18nSupportException("reason", 12), new I18nSupportException.NoStackTrace("reason", 12), + new BusinessException("reason", "BUSINESS", 409, 12), + new BusinessException.NoStackTrace("reason", "BUSINESS", 409, 12), + new NotFoundException("reason", 12), new NotFoundException.NoStackTrace("reason", 12), + new ValidationException("reason", details, 12), new ValidationException.NoStackTrace("reason", details, 12))) { + Map encoded = FastBeanCopier.copy(original, new LinkedHashMap<>()); + Map decoded = mapper.readValue(mapper.writeValueAsString(encoded), Map.class); + I18nSupportException restored = (I18nSupportException) FastBeanCopier.copy(decoded, Throwable.class); + Class expected = original instanceof NotFoundException ? NotFoundException.NoStackTrace.class + : original instanceof ValidationException ? ValidationException.NoStackTrace.class + : original instanceof BusinessException ? BusinessException.NoStackTrace.class : I18nSupportException.NoStackTrace.class; + Assert.assertTrue(expected.isInstance(restored)); + Assert.assertEquals(0, restored.getStackTrace().length); + Assert.assertEquals(original.getMessage(), restored.getMessage()); + Assert.assertEquals(restored.getMessage(), FastBeanCopier.getProperty(restored, "message")); + Assert.assertEquals(original.getI18nCode(), restored.getI18nCode()); + Assert.assertArrayEquals(original.getArgs(), restored.getArgs()); + Assert.assertEquals(original.getClass().getName(), ((RemoteExceptionMetadata) restored).getRemoteType()); + Assert.assertEquals(encoded.get("detail"), ((RemoteExceptionMetadata) restored).getRemoteDetail()); + Assert.assertTrue(original.getClass().isInstance(FastBeanCopier.copy(decoded, original.getClass()))); + if (original instanceof BusinessException business) { + Assert.assertEquals(business.getStatus(), ((BusinessException) restored).getStatus()); + Assert.assertEquals(business.getCode(), ((BusinessException) restored).getCode()); + } + if (restored instanceof ValidationException validation) { + Assert.assertEquals("field", validation.getDetails().get(0).getProperty()); + Assert.assertEquals("invalid", validation.getDetails().get(0).getMessage()); + Assert.assertEquals("extra", validation.getDetails().get(0).getDetail()); + Assert.assertEquals(encoded.get("details"), FastBeanCopier.copy(restored, new LinkedHashMap<>()).get("details")); + } + } + } + + @Test + public void concretePlatformBeanFieldsRestoreTheirOwnFamilies() { + Map source = Map.of( + "missing", FastBeanCopier.copy(new NotFoundException("missing"), new LinkedHashMap<>()), + "invalid", FastBeanCopier.copy(new ValidationException("field", "invalid"), new LinkedHashMap<>()), + "reason", FastBeanCopier.copy(new I18nSupportException("reason"), new LinkedHashMap<>())); + + PlatformHolder restored = FastBeanCopier.copy(source, new PlatformHolder()); + + Assert.assertTrue(restored.getMissing() instanceof NotFoundException.NoStackTrace); + Assert.assertTrue(restored.getInvalid() instanceof ValidationException.NoStackTrace); + Assert.assertTrue(restored.getReason() instanceof I18nSupportException.NoStackTrace); + } + + @Test + public void validationWithoutDetailsKeepsTheFieldAbsent() { + for (ValidationException original : List.of(new ValidationException("reason"), new ValidationException.NoStackTrace("reason"))) { + Map encoded = FastBeanCopier.copy(original, new LinkedHashMap<>()); + ValidationException restored = FastBeanCopier.copy(encoded, ValidationException.class); + Assert.assertNull(restored.getDetails()); + Assert.assertFalse(FastBeanCopier.copy(restored, new LinkedHashMap<>()).containsKey("details")); + } + } + + @Test + public void inconsistentNotFoundBusinessFieldsAreRejected() { + for (Map invalid : List.of( + Map.of("type", NotFoundException.class.getName(), "message", "missing", "status", 409), + Map.of("type", NotFoundException.class.getName(), "message", "missing", "code", "conflict"))) { + Assert.assertThrows(IllegalArgumentException.class, () -> FastBeanCopier.copy(invalid, Throwable.class)); + } + } + + @Test + public void beanAndRecordFieldsRestoreDescriptions() { + Map source = Map.of("error", description()); + + Throwable bean = FastBeanCopier.copy(source, new ThrowableHolder()).getError(); + BusinessException business = FastBeanCopier.copy(source, new BusinessHolder()).getError(); + Throwable record = FastBeanCopier.copy(source, ErrorRecord.class).error(); + + Assert.assertEquals("failed", bean.getMessage()); + Assert.assertEquals("failed", business.getMessage()); + Assert.assertEquals("failed", record.getMessage()); + Assert.assertEquals(409, FastBeanCopier.copy(Map.of("error", + Map.of("type", "remote.Business", "message", "failed", "status", 409)), new BusinessHolder()).getError().getStatus()); + } + + @Test + public void jsonRoundTripRestoresBusinessDataAndTypedArguments() throws Exception { + BusinessException original = new BusinessException("reason", "BUSINESS", 409, 12); + Map encoded = FastBeanCopier.copy(original, new LinkedHashMap<>()); + ObjectMapper mapper = new ObjectMapper(); + Map decoded = mapper.readValue(mapper.writeValueAsString(Map.of("error", encoded)), Map.class); + + BusinessException restored = FastBeanCopier.copy(decoded, new BusinessHolder()).getError(); + + Assert.assertEquals(original.getMessage(), restored.getMessage()); + Assert.assertEquals("reason", restored.getI18nCode()); + Assert.assertEquals("BUSINESS", restored.getCode()); + Assert.assertEquals(409, restored.getStatus()); + Assert.assertArrayEquals(new Object[]{12}, restored.getArgs()); + Assert.assertEquals(encoded.get("detail"), ((RemoteException) restored).getRemoteDetail()); + } + + @Test + public void restoredBusinessRetainsSerializableMetadata() throws Exception { + BusinessException original = new BusinessException("reason", "BUSINESS", 409, 12); + Map encoded = FastBeanCopier.copy(original, new LinkedHashMap<>()); + BusinessException restored = FastBeanCopier.copy(encoded, BusinessException.class); + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ObjectOutputStream output = new ObjectOutputStream(bytes)) { + output.writeObject(restored); + } + try (ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { + BusinessException decoded = (BusinessException) input.readObject(); + Assert.assertEquals(restored.getMessage(), decoded.getMessage()); + Assert.assertEquals("BUSINESS", decoded.getCode()); + Assert.assertEquals(409, decoded.getStatus()); + Assert.assertEquals(encoded.get("type"), ((RemoteExceptionMetadata) decoded).getRemoteType()); + Assert.assertEquals(encoded.get("detail"), ((RemoteExceptionMetadata) decoded).getRemoteDetail()); + } + } + + @Test + public void repeatedHopsRetainOriginalDescriptionAndMissingFields() { + Map encoded = description(); + for (int i = 0; i < 3; i++) { + Throwable restored = FastBeanCopier.copy(encoded, Throwable.class); + encoded = FastBeanCopier.copy(restored, new LinkedHashMap<>()); + Assert.assertEquals(description(), encoded); + } + Throwable typeOnly = FastBeanCopier.copy(Map.of("type", "remote.Unknown"), Throwable.class); + Assert.assertNull(typeOnly.getMessage()); + Assert.assertEquals(Map.of("type", "remote.Unknown"), FastBeanCopier.copy(typeOnly, new LinkedHashMap<>())); + } + + @Test + public void directTargetsReturnNewExceptionsAndHonorFiltering() { + Throwable existing = new Throwable("local"); + + Throwable restored = FastBeanCopier.copy(description(), existing); + Assert.assertNotSame(existing, restored); + Assert.assertEquals("failed", restored.getMessage()); + Assert.assertEquals("local", existing.getMessage()); + Assert.assertNull(((RemoteException) FastBeanCopier.copy(description(), Throwable.class, "detail")).getRemoteDetail()); + Assert.assertNull(((RemoteException) FastBeanCopier.copy(description(), new Throwable(), + FastBeanCopier.include("type", "message"))).getRemoteDetail()); + Assert.assertEquals("failed", FastBeanCopier.DEFAULT_CONVERT.convert(description(), Throwable.class, + FastBeanCopier.EMPTY_CLASS_ARRAY).getMessage()); + } + + @Test + public void objectAndMapTargetsDoNotAutomaticallyRestoreDescriptions() { + Map description = description(); + ObjectHolder holder = FastBeanCopier.copy(Map.of("error", description), new ObjectHolder()); + + Assert.assertSame(description, holder.getError()); + Assert.assertSame(description, FastBeanCopier.copy(Map.of("error", description), new LinkedHashMap<>()).get("error")); + Assert.assertSame(description, FastBeanCopier.DEFAULT_CONVERT.convert(description, Object.class, + FastBeanCopier.EMPTY_CLASS_ARRAY)); + } + + @Test + public void arraysAndListsPreserveArgumentTypesWithoutSharingTheContainer() { + Object[] args = {12, "value"}; + Map source = new LinkedHashMap<>(description()); + source.put("args", args); + RemoteException array = (RemoteException) FastBeanCopier.copy(source, Throwable.class); + Assert.assertArrayEquals(args, array.getArgs()); + Assert.assertNotSame(args, array.getArgs()); + + source.put("args", List.of(12, "value")); + RemoteException list = (RemoteException) FastBeanCopier.copy(source, Throwable.class); + Assert.assertArrayEquals(args, list.getArgs()); + } + + @Test + public void untrustedTypeIsMetadataAndNeverInitializesTheNamedClass() { + Throwable restored = FastBeanCopier.copy(Map.of("type", ClassNameTrap.class.getName(), "message", "remote"), Throwable.class); + + Assert.assertEquals(0, TrapCounter.initializations); + Assert.assertEquals(ClassNameTrap.class.getName(), ((RemoteException) restored).getRemoteType()); + } + + @Test + public void unsupportedTargetsAndIncompatibleLiveValuesFailExplicitly() { + for (Class target : List.of(IllegalStateException.class, Error.class)) { + Assert.assertThrows(UnsupportedOperationException.class, () -> FastBeanCopier.copy(description(), target)); + } + Assert.assertThrows(IllegalArgumentException.class, + () -> FastBeanCopier.copy(new AssertionError("local"), RuntimeException.class)); + Assert.assertThrows(IllegalArgumentException.class, + () -> FastBeanCopier.DEFAULT_CONVERT.convert("failed", Throwable.class, FastBeanCopier.EMPTY_CLASS_ARRAY)); + } + + @Test + public void malformedDescriptionFieldsAreRejected() { + for (Map invalid : List.>of(Map.of(), Map.of("type", ""), Map.of("type", 1), + Map.of("type", "remote", "message", 1), Map.of("type", "remote", "detail", 1), + Map.of("type", "remote", "i18nCode", 1), Map.of("type", "remote", "code", 1), + Map.of("type", "remote", "args", "value"), Map.of("type", "remote", "args", new int[]{1}))) { + Assert.assertThrows(IllegalArgumentException.class, () -> FastBeanCopier.copy(invalid, Throwable.class)); + } + for (Object details : List.of("invalid", List.of("invalid"), List.of(Map.of("property", 1)), List.of(Map.of("message", 1)))) { + Assert.assertThrows(IllegalArgumentException.class, + () -> FastBeanCopier.copy(Map.of("type", "remote", "details", details), Throwable.class)); + } + } + + @Test + public void statusRequiresAnExactIntAndAcceptsJsonNumberForms() { + for (Object invalid : new Object[]{"409", 409.5, Long.MAX_VALUE, Double.NaN}) { + Map source = new LinkedHashMap<>(description()); + source.put("status", invalid); + Assert.assertThrows(IllegalArgumentException.class, () -> FastBeanCopier.copy(source, Throwable.class)); + } + for (Number valid : List.of(409, 409L, new BigDecimal("409.0"))) { + Map source = new LinkedHashMap<>(description()); + source.put("status", valid); + Assert.assertEquals(409, FastBeanCopier.copy(source, BusinessException.class).getStatus()); + } + } + + private Map description() { + return Map.of("type", "remote.Problem", "message", "failed", "detail", "remote stack"); + } + + public static class ThrowableHolder { + private Throwable error; + public Throwable getError() { return error; } + public void setError(Throwable error) { this.error = error; } + } + + public static class BusinessHolder { + private BusinessException error; + public BusinessException getError() { return error; } + public void setError(BusinessException error) { this.error = error; } + } + + public static class ObjectHolder { + private Object error; + public Object getError() { return error; } + public void setError(Object error) { this.error = error; } + } + + public static class ErrorList { + private List errors; + public List getErrors() { return errors; } + public void setErrors(List errors) { this.errors = errors; } + } + + public static class PlatformHolder { + private NotFoundException missing; + private ValidationException invalid; + private I18nSupportException reason; + public NotFoundException getMissing() { return missing; } + public void setMissing(NotFoundException missing) { this.missing = missing; } + public ValidationException getInvalid() { return invalid; } + public void setInvalid(ValidationException invalid) { this.invalid = invalid; } + public I18nSupportException getReason() { return reason; } + public void setReason(I18nSupportException reason) { this.reason = reason; } + } + + public record ErrorRecord(Throwable error) { + } + + public static class TrapCounter { + static int initializations; + } + + public static class ClassNameTrap extends RuntimeException { + static { TrapCounter.initializations++; } + } +} diff --git a/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java index 6edb14820..647eab1e8 100644 --- a/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java +++ b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java @@ -5,6 +5,7 @@ import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; @@ -23,7 +24,7 @@ public class FastBeanCopierExceptionSpiTest { @Test public void serviceLoaderCustomizesDetailAndKeepsFilteringLazy() throws Exception { Path root = Files.createTempDirectory("exception-map-spi"); - String serviceName = "META-INF/services/" + ExceptionToMapConverter.class.getName(); + String serviceName = "META-INF/services/" + ExceptionConverter.class.getName(); Path service = root.resolve(serviceName); Files.createDirectories(service.getParent()); Files.writeString(service, CustomConverter.class.getName()); @@ -77,6 +78,26 @@ public Enumeration getResources(String name) throws IOException { Assert.assertEquals("custom", full.get("extra")); Assert.assertEquals("failed", full.get("message")); Assert.assertEquals(1, CustomConverter.detailReads); + + Method restore = isolated.getMethod("copy", Object.class, Class.class, String[].class); + Throwable remote = (Throwable) restore.invoke(null, + Map.of("type", "remote.Foreign", "message", "remote", "detail", "original remote stack"), + Throwable.class, new String[0]); + Map forwarded = new LinkedHashMap<>(); + copy.invoke(null, remote, forwarded, new String[0]); + Assert.assertEquals("remote.Foreign", forwarded.get("type")); + Assert.assertEquals("original remote stack", forwarded.get("detail")); + Assert.assertEquals(1, CustomConverter.detailReads); + Throwable restored = (Throwable) restore.invoke(null, Map.of("type", "remote.Custom", "message", "restored"), + CustomException.class, new String[0]); + Assert.assertTrue(restored instanceof CustomException); + Assert.assertEquals("restored", restored.getMessage()); + for (String invalid : new String[]{"wrongType", "nullResult"}) { + InvocationTargetException failure = Assert.assertThrows(InvocationTargetException.class, + () -> restore.invoke(null, Map.of("type", "remote.Custom", invalid, true), + CustomException.class, new String[0])); + Assert.assertTrue(failure.getCause() instanceof UnsupportedOperationException); + } } finally { thread.setContextClassLoader(original); try (Stream files = Files.walk(root)) { @@ -87,12 +108,12 @@ public Enumeration getResources(String name) throws IOException { } } - public static class CustomConverter extends DefaultExceptionToMapConverter { + public static class CustomConverter extends DefaultExceptionConverter { static int detailReads; @Override - public void convert(Throwable source, BiConsumer> properties) { - super.convert(source, properties); + public void toMap(Throwable source, BiConsumer> properties) { + super.toMap(source, properties); properties.accept("extra", () -> "custom"); } @@ -101,5 +122,25 @@ protected String getDetail(Throwable source) { detailReads++; return "compact:" + source.getMessage(); } + + @Override + public Throwable fromMap(Map source, Class targetType) { + if (source.containsKey("wrongType")) { + return new AssertionError("wrong type"); + } + if (source.containsKey("nullResult")) { + return null; + } + if (targetType == CustomException.class) { + return new CustomException((String) source.get("message")); + } + return super.fromMap(source, targetType); + } + } + + public static class CustomException extends RuntimeException { + public CustomException(String message) { + super(message); + } } } diff --git a/hsweb-core/src/test/java/org/hswebframework/web/i18n/RemoteExceptionI18nTest.java b/hsweb-core/src/test/java/org/hswebframework/web/i18n/RemoteExceptionI18nTest.java new file mode 100644 index 000000000..ae6be0269 --- /dev/null +++ b/hsweb-core/src/test/java/org/hswebframework/web/i18n/RemoteExceptionI18nTest.java @@ -0,0 +1,113 @@ +package org.hswebframework.web.i18n; + +import org.hswebframework.web.bean.FastBeanCopier; +import org.hswebframework.web.exception.BusinessException; +import org.hswebframework.web.exception.RemoteException; +import org.hswebframework.web.exception.RemoteExceptionMetadata; +import org.hswebframework.web.exception.I18nSupportException; +import org.hswebframework.web.exception.NotFoundException; +import org.hswebframework.web.exception.ValidationException; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.MessageSource; +import org.springframework.context.support.StaticMessageSource; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +public class RemoteExceptionI18nTest { + private MessageSource previous; + + @Before + public void installMessages() { + previous = LocaleUtils.messageSource; + StaticMessageSource messages = new StaticMessageSource(); + messages.addMessage("test.restore.reason", Locale.ENGLISH, "Rejected {0,number,integer}"); + messages.addMessage("test.restore.reason", Locale.CHINESE, "拒绝 {0,number,integer}"); + LocaleUtils.messageSource = messages; + } + + @After + public void restoreMessages() { + LocaleUtils.messageSource = previous; + } + + @Test + public void restoredReasonRetranslatesNumericArgumentsAndSurvivesHops() { + Map source = Map.of("type", "remote.BusinessProblem", "message", "Sender fallback", + "detail", "remote stack", "i18nCode", "test.restore.reason", "args", List.of(12), + "code", "BUSINESS_REJECTED", "status", 409); + + for (Locale locale : List.of(Locale.CHINESE, Locale.ENGLISH)) { + LocaleUtils.doWith(locale, ignored -> { + Map encoded = source; + for (int i = 0; i < 3; i++) { + BusinessException restored = FastBeanCopier.copy(encoded, BusinessException.class); + Assert.assertEquals(locale.equals(Locale.CHINESE) ? "拒绝 12" : "Rejected 12", restored.getMessage()); + Assert.assertEquals(encoded.get("message"), restored.getOriginalMessage()); + Assert.assertEquals("test.restore.reason", restored.getI18nCode()); + Assert.assertArrayEquals(new Object[]{12}, restored.getArgs()); + Assert.assertEquals("BUSINESS_REJECTED", restored.getCode()); + Assert.assertEquals(409, restored.getStatus()); + encoded = FastBeanCopier.copy(restored, new LinkedHashMap<>()); + Assert.assertEquals("remote.BusinessProblem", encoded.get("type")); + Assert.assertEquals("remote stack", encoded.get("detail")); + } + }); + } + } + + @Test + public void untranslatedReasonsKeepSenderMessageAcrossHops() { + Map source = Map.of("type", "remote.Unknown", "message", "Sender text", + "i18nCode", "unknown.remote.reason", "args", List.of(12)); + + LocaleUtils.doWith(Locale.ENGLISH, ignored -> { + Map encoded = source; + for (int i = 0; i < 3; i++) { + RemoteException restored = (RemoteException) FastBeanCopier.copy(encoded, Throwable.class); + Assert.assertEquals("Sender text", restored.getMessage()); + Assert.assertEquals("unknown.remote.reason", restored.getI18nCode()); + encoded = FastBeanCopier.copy(restored, new LinkedHashMap<>()); + Assert.assertEquals("remote.Unknown", encoded.get("type")); + Assert.assertFalse(encoded.containsKey("status")); + Assert.assertFalse(encoded.containsKey("detail")); + } + }); + } + + @Test + public void nullReasonAndNullMessageRemainAbsent() { + Throwable restored = FastBeanCopier.copy(Map.of("type", "remote.Unknown"), Throwable.class); + + Assert.assertNull(restored.getMessage()); + Assert.assertEquals(Map.of("type", "remote.Unknown"), FastBeanCopier.copy(restored, new LinkedHashMap<>())); + } + + @Test + public void knownPlatformNoStackTraceTypesRetainTranslationAndSenderFallback() { + for (Class type : List.of(I18nSupportException.class, + BusinessException.class, NotFoundException.class, ValidationException.class)) { + LocaleUtils.doWith(Locale.CHINESE, ignored -> { + Map encoded = Map.of("type", type.getName(), "message", "Sender text", + "detail", "remote stack", "i18nCode", "test.restore.reason", "args", List.of(12)); + for (int i = 0; i < 3; i++) { + I18nSupportException restored = FastBeanCopier.copy(encoded, type); + Assert.assertEquals("拒绝 12", restored.getMessage()); + Assert.assertEquals(encoded.get("message"), restored.getOriginalMessage()); + Assert.assertEquals(0, restored.getStackTrace().length); + encoded = FastBeanCopier.copy(restored, new LinkedHashMap<>()); + Assert.assertEquals(type.getName(), ((RemoteExceptionMetadata) restored).getRemoteType()); + Assert.assertEquals("remote stack", encoded.get("detail")); + } + I18nSupportException unknown = FastBeanCopier.copy(Map.of("type", type.getName(), + "message", "Sender text", "i18nCode", "unknown.remote.reason"), type); + Assert.assertEquals("Sender text", unknown.getMessage()); + }); + } + } +} From b138ea00671a65914a4c8441d0092147fc193159 Mon Sep 17 00:00:00 2001 From: zhou-hao Date: Fri, 27 Nov 2026 17:30:59 +0800 Subject: [PATCH 3/5] =?UTF-8?q?fix(bean):=20=E4=BF=AE=E5=A4=8D=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E8=BF=98=E5=8E=9F=E7=9A=84=E5=9B=BD=E9=99=85=E5=8C=96?= =?UTF-8?q?=E5=9B=9E=E9=80=80=E4=B8=8E=E5=BA=8F=E5=88=97=E5=8C=96=E8=BE=B9?= =?UTF-8?q?=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 保留无译文的远端消息原文,避免重复格式化引起单引号和括号损坏。 让校验异常详情支持 Java 序列化,统一空忽略集行为。 补充循环引用、畸形输入、并发 SPI 和国际化边界回归,隔离启动配置测试。 --- hsweb-core/README.md | 4 +- .../web/bean/FastBeanCopier.java | 3 +- .../web/exception/I18nSupportException.java | 7 + .../web/exception/RemoteException.java | 21 ++ .../exception/RemoteExceptionMetadata.java | 13 ++ .../web/exception/ValidationException.java | 6 +- .../bean/FastBeanCopierExceptionEdgeTest.java | 168 +++++++++++++++ .../bean/FastBeanCopierExceptionSpiTest.java | 200 +++++++++++++----- .../web/i18n/RemoteExceptionI18nTest.java | 88 ++++++++ .../web/validator/ValidatorUtilsTest.java | 40 +++- 10 files changed, 492 insertions(+), 58 deletions(-) create mode 100644 hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionEdgeTest.java diff --git a/hsweb-core/README.md b/hsweb-core/README.md index 9d2a225ac..0736bd216 100644 --- a/hsweb-core/README.md +++ b/hsweb-core/README.md @@ -27,7 +27,7 @@ 实现位于 `hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java`,使用独立的 `PropertyUtilsBean` 和内省扩展点,不修改全局 BeanUtils 配置,复用现有代码生成、类型转换和缓存。 -Bean 属性复制每次只读取一次实际参与复制的源属性,空值保持现有跳过写入的语义;include/ignore 排除的属性不读取,getter 抛出的异常继续传播。Bean 转普通 Map 保持浅复制,嵌套的 Throwable 保留原引用,不自动展开、丢弃或转成字符串。 +Bean 属性复制每次只读取一次实际参与复制的源属性,空值保持现有跳过写入的语义;include/ignore 排除的属性不读取,getter 抛出的异常继续传播。null 忽略集合与 null varargs 均视为无忽略项。Bean 转普通 Map 保持浅复制,嵌套的 Throwable 保留原引用,不自动展开、丢弃或转成字符串。 Bean/record 转 Map 时排除 `transient` 字段(包含继承字段)及 JavaBeans `java.beans.Transient` 标记的属性,排除发生在调用 getter 前,显式 include 也不会导出这些属性。`@Transient(false)` 不排除属性,但不能覆盖字段上的 `transient`。此规则不影响 Bean→Bean、Map→Bean、Bean→record、Map→Map 和 `getProperty` 按名称取值。 @@ -37,7 +37,7 @@ Bean/record 转 Map 时排除 `transient` 字段(包含继承字段)及 Java ValidationException 的 details 以 property/message/detail 字段 Map 列表导出,恢复时保留字段错误及详情;details 中的业务值保持浅复制。已知异常固定的业务 code/status 若与描述冲突会明确拒绝,不静默丢失。鉴权等上层模块的异常由其 SPI 实现扩展,hsweb-core 不反向依赖这些模块。 -还原支持本地 Object[] 与 JSON List 形式的 args,复制参数容器并保留参数值类型;status 必须是 int 范围内的整数。接收端无对应译文时使用发送端 message 回退。恢复后的异常再次转 Map 时沿用原远端 type/detail,不生成本地替代栈;缺省字段保持缺省。`copy(map, Throwable.class)` 与 `copy(map, existingThrowable)` 采用同一恢复路径,后者返回新异常,调用方必须使用返回值;复制到普通 Bean/record 的异常字段也使用该转换规则。 +还原支持本地 Object[] 与 JSON List 形式的 args,复制参数容器并保留参数值类型;status 必须是 int 范围内的整数。接收端无对应译文时原样回退发送端 message,不再把已经渲染的文案当作 MessageFormat 模板;普通本地异常的模板格式化和校验属性翻译保持原语义。ValidationException.Detail 可随异常参与 Java 序列化,业务参数和 detail 值仍须满足所用编码器的要求。恢复后的异常再次转 Map 时沿用原远端 type/detail,不生成本地替代栈;缺省字段保持缺省。`copy(map, Throwable.class)` 与 `copy(map, existingThrowable)` 采用同一恢复路径,后者返回新异常,调用方必须使用返回值;复制到普通 Bean/record 的异常字段也使用该转换规则。 可在 `META-INF/services/org.hswebframework.web.bean.ExceptionConverter` 注册自定义双向实现(`toMap` / `fromMap`)。首次异常转换时使用线程上下文 ClassLoader 发现的首个实现,每个运行环境应只注册一个;无实现时回退 `DefaultExceptionConverter`。实例按 copier 的 ClassLoader 复用,自定义实现应无状态或线程安全。toMap 按字段提供延迟 Supplier,由 copier 统一过滤、读取及转换;继承默认实现并覆盖 `getDetail(Throwable)` 可精简原始异常的栈,自定义栈处理需保留循环引用处理。携带 RemoteExceptionMetadata 的异常直接沿用远端 detail,不再调用此栈渲染方法。fromMap 应返回与目标声明兼容的异常,copier 拒绝 null 或不兼容的 SPI 返回值。 diff --git a/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java b/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java index 6f90bd353..fdf62b0fd 100644 --- a/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java +++ b/hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java @@ -168,7 +168,8 @@ public static T copy(S source, T target, Set ignore) { } @SuppressWarnings("all") - public static T copy(S source, T target, Converter converter, Set ignore) { + public static T copy(S source, T target, Converter converter, Set ignored) { + Set ignore = ignored == null ? Collections.emptySet() : ignored; if (target instanceof Throwable) { // 异常的消息等属性不能通过 setter 修改,返回转换后的异常。 return (T) copyToThrowable(source, getUserClass(target), converter, ignore); diff --git a/hsweb-core/src/main/java/org/hswebframework/web/exception/I18nSupportException.java b/hsweb-core/src/main/java/org/hswebframework/web/exception/I18nSupportException.java index 9a5e8a787..524846ba7 100644 --- a/hsweb-core/src/main/java/org/hswebframework/web/exception/I18nSupportException.java +++ b/hsweb-core/src/main/java/org/hswebframework/web/exception/I18nSupportException.java @@ -62,6 +62,13 @@ public final String getLocalizedMessage() { } public String getLocalizedMessage(Locale locale) { + return resolveLocalizedMessage(locale, args); + } + + /** + * 子类可调整回退策略;默认 originalMessage 仍按本地消息模板解析。 + */ + protected String resolveLocalizedMessage(Locale locale, Object[] args) { return LocaleUtils.resolveMessage(i18nCode, locale, getOriginalMessage(), args); } diff --git a/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteException.java b/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteException.java index b05c141a6..4493b1469 100644 --- a/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteException.java +++ b/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteException.java @@ -2,6 +2,7 @@ import lombok.Getter; +import java.util.Locale; /** * 未知远端异常的安全包装,不加载远端类或解析堆栈。 * 已知平台异常使用对应的 NoStackTrace 实现,并携带相同的远端描述。 @@ -23,6 +24,11 @@ public String getOriginalMessage() { return remoteDescription.message(); } + @Override + protected String resolveLocalizedMessage(Locale locale, Object[] args) { + return resolveRemoteMessage(locale, args); + } + @Getter public static final class I18n extends I18nSupportException.NoStackTrace implements RemoteExceptionMetadata { private final Description remoteDescription; @@ -36,6 +42,11 @@ public I18n(Description description) { public String getOriginalMessage() { return remoteDescription.message(); } + + @Override + protected String resolveLocalizedMessage(Locale locale, Object[] args) { + return resolveRemoteMessage(locale, args); + } } @Getter @@ -51,6 +62,11 @@ public NotFound(Description description) { public String getOriginalMessage() { return remoteDescription.message(); } + + @Override + protected String resolveLocalizedMessage(Locale locale, Object[] args) { + return resolveRemoteMessage(locale, args); + } } @Getter @@ -66,5 +82,10 @@ public Validation(Description description) { public String getOriginalMessage() { return remoteDescription.message(); } + + @Override + protected String resolveLocalizedMessage(Locale locale, Object[] args) { + return resolveRemoteMessage(locale, args); + } } } diff --git a/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteExceptionMetadata.java b/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteExceptionMetadata.java index 079fc2319..530da66b8 100644 --- a/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteExceptionMetadata.java +++ b/hsweb-core/src/main/java/org/hswebframework/web/exception/RemoteExceptionMetadata.java @@ -1,9 +1,12 @@ package org.hswebframework.web.exception; +import org.hswebframework.web.i18n.LocaleUtils; import org.springframework.util.Assert; +import org.springframework.util.StringUtils; import java.io.Serializable; import java.util.List; +import java.util.Locale; /** * 恢复后的异常携带的远端描述。再次转 Map 时保留远端类型和诊断信息。 @@ -24,6 +27,16 @@ default Integer getRemoteStatus() { return getRemoteDescription().status(); } + /** + * 发送端 message 已是展示文本,不能作为 MessageFormat 模板再次格式化。 + */ + default String resolveRemoteMessage(Locale locale, Object[] args) { + Description description = getRemoteDescription(); + String translated = StringUtils.hasText(description.i18nCode()) + ? LocaleUtils.resolveMessage(description.i18nCode(), locale, null, args) : null; + return translated == null ? description.message() : translated; + } + record Description(String type, String message, String detail, diff --git a/hsweb-core/src/main/java/org/hswebframework/web/exception/ValidationException.java b/hsweb-core/src/main/java/org/hswebframework/web/exception/ValidationException.java index c793d80dd..84e3d9475 100644 --- a/hsweb-core/src/main/java/org/hswebframework/web/exception/ValidationException.java +++ b/hsweb-core/src/main/java/org/hswebframework/web/exception/ValidationException.java @@ -2,6 +2,7 @@ import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.ConstraintViolation; +import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @@ -76,7 +77,7 @@ public String getLocalizedMessage(Locale locale) { if (propertyI18nEnabled && "validation.property_validate_failed".equals(getI18nCode()) && getArgs().length > 0) { Object[] args = getArgs().clone(); args[0] = LocaleUtils.resolveMessage(String.valueOf(args[0]), locale, String.valueOf(args[0])); - return LocaleUtils.resolveMessage(getI18nCode(), locale, getOriginalMessage(), args); + return resolveLocalizedMessage(locale, args); } return super.getLocalizedMessage(locale); } @@ -84,7 +85,8 @@ public String getLocalizedMessage(Locale locale) { @Getter @Setter @AllArgsConstructor - public static class Detail { + public static class Detail implements Serializable { + private static final long serialVersionUID = 1L; @Schema(description = "字段") String property; diff --git a/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionEdgeTest.java b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionEdgeTest.java new file mode 100644 index 000000000..953e4430b --- /dev/null +++ b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionEdgeTest.java @@ -0,0 +1,168 @@ +package org.hswebframework.web.bean; + +import org.hswebframework.web.exception.BusinessException; +import org.hswebframework.web.exception.RemoteExceptionMetadata; +import org.hswebframework.web.exception.ValidationException; +import org.junit.Assert; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.PrintWriter; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +public class FastBeanCopierExceptionEdgeTest { + + @Test + public void nullIgnoreSetMatchesNullVarargsForAllCopyDirections() { + Throwable error = new IllegalStateException("failed"); + Map expected = FastBeanCopier.copy(error, new LinkedHashMap<>()); + Assert.assertEquals(expected, FastBeanCopier.copy(error, new LinkedHashMap<>(), (Set) null)); + Assert.assertEquals(expected, FastBeanCopier.copy(error, new LinkedHashMap<>(), (String[]) null)); + FastBeanCopierReadOnceTest.NameTarget source = new FastBeanCopierReadOnceTest.NameTarget(); + source.setName("one"); + Assert.assertEquals(Map.of("name", "one"), FastBeanCopier.copy(source, new LinkedHashMap<>(), (Set) null)); + Assert.assertEquals("one", FastBeanCopier.copy(Map.of("name", "one"), + new FastBeanCopierReadOnceTest.NameTarget(), (Set) null).getName()); + Assert.assertEquals("failed", FastBeanCopier.copy(expected, new Throwable(), (Set) null).getMessage()); + } + + @Test + public void cyclicCauseSuppressedAndSharedNodesRemainFinite() { + Throwable first = new IllegalStateException("first"); + Throwable second = new IllegalArgumentException("second"); + Throwable shared = new IllegalStateException("shared"); + first.initCause(second); + second.initCause(first); + first.addSuppressed(shared); + second.addSuppressed(shared); + shared.addSuppressed(first); + for (Throwable value : List.of(first, second, shared)) { + value.setStackTrace(new StackTraceElement[0]); + } + + Map encoded = FastBeanCopier.copy(first, new LinkedHashMap<>()); + String detail = (String) encoded.get("detail"); + Assert.assertTrue(detail.contains("CIRCULAR REFERENCE")); + Assert.assertTrue(detail.contains("Suppressed:")); + Assert.assertTrue(detail.contains("Caused by:")); + Assert.assertTrue(detail.length() < 4096); + Throwable restored = FastBeanCopier.copy(encoded, Throwable.class); + Assert.assertNull(restored.getCause()); + Assert.assertEquals(0, restored.getSuppressed().length); + Assert.assertEquals(detail, FastBeanCopier.copy(restored, new LinkedHashMap<>()).get("detail")); + } + + @Test + public void excludedCallbacksNeverExecuteAndErrorsAreNotSwallowed() { + BrokenException source = new BrokenException(); + Assert.assertEquals(Map.of("type", source.getClass().getName()), + FastBeanCopier.copy(source, new LinkedHashMap<>(), FastBeanCopier.include("type"))); + Assert.assertEquals(0, source.messageReads); + Assert.assertEquals(0, source.detailReads); + Assert.assertSame(source.messageFailure, Assert.assertThrows(AssertionError.class, + () -> FastBeanCopier.copy(source, new LinkedHashMap<>(), "detail"))); + Assert.assertSame(source.detailFailure, Assert.assertThrows(AssertionError.class, + () -> FastBeanCopier.copy(source, new LinkedHashMap<>(), "message"))); + } + + @Test + public void immutableInputsAndMutableDetailsDoNotChangeTheSource() { + ValidationException.Detail detail = new ValidationException.Detail("field", "invalid", Map.of("value", 12)); + List args = Collections.unmodifiableList(Arrays.asList(null, new BigDecimal("12.30"))); + Map source = Map.of("type", ValidationException.class.getName(), "message", "failed", + "args", args, "details", List.of(detail)); + ValidationException restored = FastBeanCopier.copy(source, ValidationException.class); + + Assert.assertArrayEquals(args.toArray(), restored.getArgs()); + restored.getArgs()[0] = "changed"; + restored.getDetails().get(0).setProperty("changed"); + Assert.assertNull(args.get(0)); + Assert.assertEquals("field", detail.getProperty()); + Assert.assertSame(detail.getDetail(), restored.getDetails().get(0).getDetail()); + } + + @Test + public void statusHandlesExactBoundsAndRejectsOverflowAndNonFiniteValues() { + for (Number value : List.of(Integer.MIN_VALUE, Integer.MAX_VALUE, BigInteger.valueOf(409), + new BigDecimal("409.000"), new AtomicInteger(409))) { + BusinessException restored = FastBeanCopier.copy(Map.of("type", "remote.Status", "status", value), BusinessException.class); + Assert.assertEquals(value.intValue(), restored.getStatus()); + } + for (Number value : List.of(new BigInteger("-2147483649"), new BigInteger("2147483648"), + new BigDecimal("409.0001"), Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY)) { + Assert.assertThrows(IllegalArgumentException.class, + () -> FastBeanCopier.copy(Map.of("type", "remote.Status", "status", value), Throwable.class)); + } + } + + @Test + public void unicodeLargeDiagnosticsAndRepeatedFailuresDoNotCorruptLaterConversions() { + String message = "设备\n不可用🙂\t'quoted'"; + String diagnostic = "远端诊断🙂\n".repeat(4096); + Map source = Map.of("type", "remote.Unicode", "message", message, "detail", diagnostic); + for (int i = 0; i < 50; i++) { + Assert.assertThrows(IllegalArgumentException.class, + () -> FastBeanCopier.copy(Map.of("type", 1), Throwable.class)); + Throwable restored = FastBeanCopier.copy(source, Throwable.class); + Assert.assertEquals(message, restored.getMessage()); + Assert.assertEquals(diagnostic, ((RemoteExceptionMetadata) restored).getRemoteDetail()); + } + Assert.assertEquals(source, FastBeanCopier.copy(FastBeanCopier.copy(source, Throwable.class), new LinkedHashMap<>())); + } + + @Test + public void cyclicArgumentPayloadsRemainShallowWithoutRecursiveTraversal() { + Map payload = new LinkedHashMap<>(); + payload.put("self", payload); + Throwable restored = FastBeanCopier.copy(Map.of("type", "remote.Payload", "args", List.of(payload)), Throwable.class); + Map forwarded = FastBeanCopier.copy(restored, new LinkedHashMap<>()); + Assert.assertSame(payload, ((Object[]) forwarded.get("args"))[0]); + } + + @Test + public void restoredValidationWithOrdinaryPayloadRemainsJavaSerializable() throws Exception { + ValidationException original = new ValidationException("reason", + List.of(new ValidationException.Detail("field", "invalid", "extra")), 12); + ValidationException restored = FastBeanCopier.copy(FastBeanCopier.copy(original, new LinkedHashMap<>()), ValidationException.class); + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ObjectOutputStream output = new ObjectOutputStream(bytes)) { + output.writeObject(restored); + } + try (ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { + ValidationException decoded = (ValidationException) input.readObject(); + Assert.assertEquals("field", decoded.getDetails().get(0).getProperty()); + Assert.assertEquals("extra", decoded.getDetails().get(0).getDetail()); + Assert.assertEquals(original.getClass().getName(), ((RemoteExceptionMetadata) decoded).getRemoteType()); + } + } + + public static class BrokenException extends RuntimeException { + final AssertionError messageFailure = new AssertionError("message failed"); + final AssertionError detailFailure = new AssertionError("detail failed"); + int messageReads; + int detailReads; + + @Override + public String getMessage() { + messageReads++; + throw messageFailure; + } + + @Override + public void printStackTrace(PrintWriter writer) { + detailReads++; + throw detailFailure; + } + } +} diff --git a/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java index 647eab1e8..91fad3bde 100644 --- a/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java +++ b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierExceptionSpiTest.java @@ -11,10 +11,19 @@ import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; +import java.util.ServiceConfigurationError; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.Supplier; import java.util.stream.Stream; @@ -23,15 +32,122 @@ public class FastBeanCopierExceptionSpiTest { @Test public void serviceLoaderCustomizesDetailAndKeepsFilteringLazy() throws Exception { + withProviders(CustomConverter.class.getName(), isolated -> { + CustomConverter.detailReads = 0; + Method copy = isolated.getMethod("copy", Object.class, Object.class, String[].class); + Throwable error = new IllegalStateException("failed"); + + Map filtered = new LinkedHashMap<>(); + Assert.assertSame(filtered, copy.invoke(null, error, filtered, new String[]{"message", "detail"})); + Assert.assertEquals(Map.of("type", error.getClass().getName(), "extra", "custom"), filtered); + Assert.assertEquals(0, CustomConverter.detailReads); + + Map full = new LinkedHashMap<>(); + copy.invoke(null, error, full, new String[0]); + Assert.assertEquals("compact:failed", full.get("detail")); + Assert.assertEquals("custom", full.get("extra")); + Assert.assertEquals("failed", full.get("message")); + Assert.assertEquals(1, CustomConverter.detailReads); + + Method restore = isolated.getMethod("copy", Object.class, Class.class, String[].class); + Throwable remote = (Throwable) restore.invoke(null, + Map.of("type", "remote.Foreign", "message", "remote", "detail", "original remote stack"), + Throwable.class, new String[0]); + Map forwarded = new LinkedHashMap<>(); + copy.invoke(null, remote, forwarded, new String[0]); + Assert.assertEquals("remote.Foreign", forwarded.get("type")); + Assert.assertEquals("original remote stack", forwarded.get("detail")); + Assert.assertEquals(1, CustomConverter.detailReads); + Throwable restored = (Throwable) restore.invoke(null, Map.of("type", "remote.Custom", "message", "restored"), + CustomException.class, new String[0]); + Assert.assertTrue(restored instanceof CustomException); + Assert.assertEquals("restored", restored.getMessage()); + for (String invalid : new String[]{"wrongType", "nullResult"}) { + InvocationTargetException failure = Assert.assertThrows(InvocationTargetException.class, + () -> restore.invoke(null, Map.of("type", "remote.Custom", invalid, true), + CustomException.class, new String[0])); + Assert.assertTrue(failure.getCause() instanceof UnsupportedOperationException); + } + }); + } + + @Test + public void coldConcurrentInitializationCreatesOnlyTheFirstProvider() throws Exception { + FirstConverter.constructions.set(0); + SecondConverter.constructions.set(0); + withProviders(FirstConverter.class.getName() + "\n" + SecondConverter.class.getName(), isolated -> { + Method copy = isolated.getMethod("copy", Object.class, Object.class, String[].class); + ExecutorService workers = Executors.newFixedThreadPool(8); + CountDownLatch start = new CountDownLatch(1); + try { + List> tasks = new ArrayList<>(); + for (int i = 0; i < 8; i++) { + tasks.add(workers.submit(() -> { + start.await(); + Map result = new LinkedHashMap<>(); + copy.invoke(null, new IllegalStateException("failed"), result, new String[]{"message", "detail"}); + Assert.assertEquals(Map.of("type", IllegalStateException.class.getName(), "provider", "first"), result); + return null; + })); + } + start.countDown(); + for (Future task : tasks) { + task.get(15, TimeUnit.SECONDS); + } + Assert.assertEquals(1, FirstConverter.constructions.get()); + Assert.assertEquals(0, SecondConverter.constructions.get()); + } finally { + start.countDown(); + workers.shutdownNow(); + Assert.assertTrue(workers.awaitTermination(15, TimeUnit.SECONDS)); + } + }); + } + + @Test + public void invalidServiceAndConstructorFailureStayVisibleWithoutBreakingOrdinaryCopy() throws Exception { + for (String provider : List.of("missing.ExceptionConverter", BrokenConstructor.class.getName())) { + withProviders(provider, isolated -> { + Method copy = isolated.getMethod("copy", Object.class, Object.class, String[].class); + InvocationTargetException first = Assert.assertThrows(InvocationTargetException.class, + () -> copy.invoke(null, new IllegalStateException("failed"), new LinkedHashMap<>(), new String[0])); + Assert.assertTrue(first.getCause() instanceof ServiceConfigurationError); + InvocationTargetException again = Assert.assertThrows(InvocationTargetException.class, + () -> copy.invoke(null, new IllegalStateException("failed"), new LinkedHashMap<>(), new String[0])); + Assert.assertTrue(again.getCause() instanceof NoClassDefFoundError); + Map ordinary = new LinkedHashMap<>(); + copy.invoke(null, Map.of("value", 12), ordinary, new String[0]); + Assert.assertEquals(Map.of("value", 12), ordinary); + Method typed = isolated.getMethod("copy", Object.class, Class.class, String[].class); + Throwable live = new IllegalStateException("live"); + Assert.assertSame(live, typed.invoke(null, live, Throwable.class, new String[0])); + }); + } + } + + @Test + public void providerMappingErrorPropagatesButDoesNotPoisonTheInitializedProvider() throws Exception { + withProviders(BrokenMapping.class.getName(), isolated -> { + Method typed = isolated.getMethod("copy", Object.class, Class.class, String[].class); + InvocationTargetException failure = Assert.assertThrows(InvocationTargetException.class, + () -> typed.invoke(null, Map.of("type", "remote.Error"), Throwable.class, new String[0])); + Assert.assertSame(BrokenMapping.failure, failure.getCause()); + Method copy = isolated.getMethod("copy", Object.class, Object.class, String[].class); + Map result = new LinkedHashMap<>(); + copy.invoke(null, new IllegalStateException("still usable"), result, new String[]{"detail"}); + Assert.assertEquals("still usable", result.get("message")); + }); + } + + private void withProviders(String providers, Check check) throws Exception { Path root = Files.createTempDirectory("exception-map-spi"); String serviceName = "META-INF/services/" + ExceptionConverter.class.getName(); Path service = root.resolve(serviceName); Files.createDirectories(service.getParent()); - Files.writeString(service, CustomConverter.class.getName()); + Files.writeString(service, providers); Thread thread = Thread.currentThread(); ClassLoader original = thread.getContextClassLoader(); String copierName = FastBeanCopier.class.getName(); - try (URLClassLoader loader = new URLClassLoader(new URL[]{root.toUri().toURL()}, getClass().getClassLoader()) { @Override protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { @@ -62,42 +178,7 @@ public Enumeration getResources(String name) throws IOException { } }) { thread.setContextClassLoader(loader); - CustomConverter.detailReads = 0; - Class isolated = Class.forName(copierName, true, loader); - Method copy = isolated.getMethod("copy", Object.class, Object.class, String[].class); - Throwable error = new IllegalStateException("failed"); - - Map filtered = new LinkedHashMap<>(); - Assert.assertSame(filtered, copy.invoke(null, error, filtered, new String[]{"message", "detail"})); - Assert.assertEquals(Map.of("type", error.getClass().getName(), "extra", "custom"), filtered); - Assert.assertEquals(0, CustomConverter.detailReads); - - Map full = new LinkedHashMap<>(); - copy.invoke(null, error, full, new String[0]); - Assert.assertEquals("compact:failed", full.get("detail")); - Assert.assertEquals("custom", full.get("extra")); - Assert.assertEquals("failed", full.get("message")); - Assert.assertEquals(1, CustomConverter.detailReads); - - Method restore = isolated.getMethod("copy", Object.class, Class.class, String[].class); - Throwable remote = (Throwable) restore.invoke(null, - Map.of("type", "remote.Foreign", "message", "remote", "detail", "original remote stack"), - Throwable.class, new String[0]); - Map forwarded = new LinkedHashMap<>(); - copy.invoke(null, remote, forwarded, new String[0]); - Assert.assertEquals("remote.Foreign", forwarded.get("type")); - Assert.assertEquals("original remote stack", forwarded.get("detail")); - Assert.assertEquals(1, CustomConverter.detailReads); - Throwable restored = (Throwable) restore.invoke(null, Map.of("type", "remote.Custom", "message", "restored"), - CustomException.class, new String[0]); - Assert.assertTrue(restored instanceof CustomException); - Assert.assertEquals("restored", restored.getMessage()); - for (String invalid : new String[]{"wrongType", "nullResult"}) { - InvocationTargetException failure = Assert.assertThrows(InvocationTargetException.class, - () -> restore.invoke(null, Map.of("type", "remote.Custom", invalid, true), - CustomException.class, new String[0])); - Assert.assertTrue(failure.getCause() instanceof UnsupportedOperationException); - } + check.accept(Class.forName(copierName, true, loader)); } finally { thread.setContextClassLoader(original); try (Stream files = Files.walk(root)) { @@ -108,6 +189,10 @@ public Enumeration getResources(String name) throws IOException { } } + private interface Check { + void accept(Class copier) throws Exception; + } + public static class CustomConverter extends DefaultExceptionConverter { static int detailReads; @@ -125,22 +210,39 @@ protected String getDetail(Throwable source) { @Override public Throwable fromMap(Map source, Class targetType) { - if (source.containsKey("wrongType")) { - return new AssertionError("wrong type"); - } - if (source.containsKey("nullResult")) { - return null; - } - if (targetType == CustomException.class) { - return new CustomException((String) source.get("message")); - } + if (source.containsKey("wrongType")) return new AssertionError("wrong type"); + if (source.containsKey("nullResult")) return null; + if (targetType == CustomException.class) return new CustomException((String) source.get("message")); return super.fromMap(source, targetType); } } public static class CustomException extends RuntimeException { - public CustomException(String message) { - super(message); + public CustomException(String message) { super(message); } + } + + public static class FirstConverter extends DefaultExceptionConverter { + static final AtomicInteger constructions = new AtomicInteger(); + public FirstConverter() { constructions.incrementAndGet(); } + @Override + public void toMap(Throwable source, BiConsumer> properties) { + super.toMap(source, properties); + properties.accept("provider", () -> "first"); } } + + public static class SecondConverter extends DefaultExceptionConverter { + static final AtomicInteger constructions = new AtomicInteger(); + public SecondConverter() { constructions.incrementAndGet(); } + } + + public static class BrokenConstructor extends DefaultExceptionConverter { + public BrokenConstructor() { throw new IllegalStateException("constructor failed"); } + } + + public static class BrokenMapping extends DefaultExceptionConverter { + static final AssertionError failure = new AssertionError("mapping failed"); + @Override + public Throwable fromMap(Map source, Class targetType) { throw failure; } + } } diff --git a/hsweb-core/src/test/java/org/hswebframework/web/i18n/RemoteExceptionI18nTest.java b/hsweb-core/src/test/java/org/hswebframework/web/i18n/RemoteExceptionI18nTest.java index ae6be0269..8f687d0ae 100644 --- a/hsweb-core/src/test/java/org/hswebframework/web/i18n/RemoteExceptionI18nTest.java +++ b/hsweb-core/src/test/java/org/hswebframework/web/i18n/RemoteExceptionI18nTest.java @@ -18,6 +18,14 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.ArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.text.MessageFormat; public class RemoteExceptionI18nTest { private MessageSource previous; @@ -110,4 +118,84 @@ public void knownPlatformNoStackTraceTypesRetainTranslationAndSenderFallback() { }); } } + + @Test + public void untranslatedSenderTextIsLiteralEvenWithQuotesAndBraces() { + for (String type : List.of("remote.Unknown", I18nSupportException.class.getName(), BusinessException.class.getName(), + NotFoundException.class.getName(), ValidationException.class.getName())) { + for (String message : List.of("can't retry {0}", "JSON {\"port\":80}", "user 'alpha' {0}")) { + Throwable restored = FastBeanCopier.copy(Map.of("type", type, "message", message, + "i18nCode", "unknown.remote.reason", "args", List.of(12)), Throwable.class); + Assert.assertEquals(message, restored.getMessage()); + } + } + } + + @Test + public void messagesWithoutI18nCodeRemainLiteralWhenFormattingIsForced() { + ((StaticMessageSource) LocaleUtils.messageSource).setAlwaysUseMessageFormat(true); + for (String message : List.of("can't retry", "JSON {\"port\":80}")) { + Throwable restored = FastBeanCopier.copy(Map.of("type", "remote.Unknown", "message", message), Throwable.class); + Assert.assertEquals(message, restored.getMessage()); + } + } + + @Test + public void localFallbackTemplatesStillFormatNormally() { + Assert.assertEquals("Local 12", new I18nSupportException("Local {0}", 12).getMessage()); + } + + @Test + public void changingMessageSourceIsQueriedOnceAndNeverReformatsTheSenderText() { + AtomicInteger lookups = new AtomicInteger(); + LocaleUtils.messageSource = new StaticMessageSource() { + @Override + protected MessageFormat resolveCode(String code, Locale locale) { + return lookups.incrementAndGet() == 1 ? new MessageFormat("Translated {0}", locale) : null; + } + }; + String sender = "JSON {\"port\":80}"; + Throwable restored = FastBeanCopier.copy(Map.of("type", ValidationException.class.getName(), "message", sender, + "i18nCode", "volatile.reason", "args", List.of(12)), Throwable.class); + Assert.assertEquals("Translated 12", restored.getMessage()); + Assert.assertEquals(1, lookups.get()); + Assert.assertEquals(sender, restored.getMessage()); + Assert.assertEquals(2, lookups.get()); + } + + @Test + public void parallelLocalesAndRepeatedHopsDoNotLeakState() throws Exception { + ExecutorService workers = Executors.newFixedThreadPool(8); + CountDownLatch start = new CountDownLatch(1); + try { + List> tasks = new ArrayList<>(); + for (int worker = 0; worker < 8; worker++) { + Locale locale = worker % 2 == 0 ? Locale.CHINESE : Locale.ENGLISH; + tasks.add(workers.submit(() -> { + start.await(); + LocaleUtils.doWith(locale, ignored -> { + Map source = Map.of("type", "remote.Concurrent", "message", "Sender", + "detail", "remote stack", "i18nCode", "test.restore.reason", "args", List.of(12)); + for (int round = 0; round < 100; round++) { + Throwable restored = FastBeanCopier.copy(source, Throwable.class); + Assert.assertEquals(locale.equals(Locale.CHINESE) ? "拒绝 12" : "Rejected 12", restored.getMessage()); + Map forwarded = FastBeanCopier.copy(restored, new LinkedHashMap<>()); + Assert.assertEquals("remote.Concurrent", forwarded.get("type")); + Assert.assertEquals("remote stack", forwarded.get("detail")); + Assert.assertEquals(List.of(12), source.get("args")); + } + }); + return null; + })); + } + start.countDown(); + for (Future task : tasks) { + task.get(15, TimeUnit.SECONDS); + } + } finally { + start.countDown(); + workers.shutdownNow(); + Assert.assertTrue(workers.awaitTermination(15, TimeUnit.SECONDS)); + } + } } diff --git a/hsweb-core/src/test/java/org/hswebframework/web/validator/ValidatorUtilsTest.java b/hsweb-core/src/test/java/org/hswebframework/web/validator/ValidatorUtilsTest.java index b5320322b..bdd536f65 100644 --- a/hsweb-core/src/test/java/org/hswebframework/web/validator/ValidatorUtilsTest.java +++ b/hsweb-core/src/test/java/org/hswebframework/web/validator/ValidatorUtilsTest.java @@ -3,25 +3,54 @@ import lombok.Getter; import lombok.Setter; import org.hswebframework.web.exception.ValidationException; +import org.hswebframework.web.bean.FastBeanCopier; import org.hswebframework.web.i18n.LocaleUtils; import org.hswebframework.web.i18n.MessageSourceInitializer; import org.junit.Test; import org.springframework.context.support.StaticMessageSource; +import org.springframework.core.OverridingClassLoader; import jakarta.validation.constraints.NotBlank; import java.util.Locale; +import java.util.LinkedHashMap; +import java.lang.reflect.InvocationTargetException; import static org.junit.Assert.*; public class ValidatorUtilsTest { - static { - System.setProperty("i18n.validation.property.enabled", "true"); + @Test + public void test() throws Throwable { + String key = "i18n.validation.property.enabled"; + String previous = System.getProperty(key); + Thread thread = Thread.currentThread(); + ClassLoader context = thread.getContextClassLoader(); + // 开关在类初始化时读取,隔离启动配置及消息源,避免依赖其他测试的加载顺序。 + ClassLoader isolated = new OverridingClassLoader(getClass().getClassLoader()) { + @Override + protected boolean isEligibleForOverriding(String name) { + return name.startsWith("org.hswebframework.web."); + } + }; + try { + System.setProperty(key, "true"); + thread.setContextClassLoader(isolated); + Class type = isolated.loadClass(getClass().getName()); + type.getMethod("verifyLocalizedProperties").invoke(type.getConstructor().newInstance()); + } catch (InvocationTargetException e) { + throw e.getCause(); + } finally { + thread.setContextClassLoader(context); + if (previous == null) { + System.clearProperty(key); + } else { + System.setProperty(key, previous); + } + } } - @Test - public void test() { + public void verifyLocalizedProperties() { StaticMessageSource source = new StaticMessageSource(); source.addMessage("validation.property_validate_failed", Locale.CHINA, "{0} {1}"); source.addMessage("validation.property_validate_failed", Locale.ENGLISH, "{0} {1}"); @@ -43,6 +72,9 @@ public void test(Locale locale, String msg, String msg2) { } catch (ValidationException e) { assertEquals(msg, e.getDetails().get(0).getMessage()); assertEquals(msg2, e.getLocalizedMessage(locale)); + ValidationException restored = FastBeanCopier.copy(FastBeanCopier.copy(e, new LinkedHashMap<>()), ValidationException.class); + assertEquals(msg2, restored.getLocalizedMessage(locale)); + assertArrayEquals(e.getArgs(), restored.getArgs()); } } From 49737866bec73587deede0baa463eeca8907d92e Mon Sep 17 00:00:00 2001 From: zhou-hao Date: Fri, 27 Nov 2026 17:49:24 +0800 Subject: [PATCH 4/5] =?UTF-8?q?test(bean):=20=E8=A6=86=E7=9B=96=E5=85=B6?= =?UTF-8?q?=E4=BB=96=E5=BC=82=E5=B8=B8=E6=97=8F=E7=9A=84=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 验证常见检查异常、运行时异常、Error、包装异常和自定义平台子类, 确保描述中转保留元数据、兼容实例直通及未知具体目标明确失败。 --- .../FastBeanCopierOtherExceptionTest.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierOtherExceptionTest.java diff --git a/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierOtherExceptionTest.java b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierOtherExceptionTest.java new file mode 100644 index 000000000..dd4189b73 --- /dev/null +++ b/hsweb-core/src/test/java/org/hswebframework/web/bean/FastBeanCopierOtherExceptionTest.java @@ -0,0 +1,78 @@ +package org.hswebframework.web.bean; + +import org.hswebframework.web.exception.BusinessException; +import org.hswebframework.web.exception.I18nSupportException; +import org.hswebframework.web.exception.RemoteException; +import org.hswebframework.web.exception.RemoteExceptionMetadata; +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CompletionException; + +public class FastBeanCopierOtherExceptionTest { + + @Test + public void otherExceptionFamiliesUseSafeDescriptionsAndRetainCompatibleLiveValues() { + Throwable cause = new IllegalStateException("cause"); + for (Throwable original : Arrays.asList( + new Throwable("root"), new Exception("checked"), new IOException("io"), + new NullPointerException("null"), new IllegalArgumentException("argument"), + new AssertionError("assertion"), new LinkageError("linkage"), + new CompletionException("completion", cause), new InvocationTargetException(cause, "invocation"), + new CustomException("custom"), new CustomI18nException("custom.i18n", 12), + new CustomBusinessException("custom.business", "CUSTOM", 409, 12))) { + Map encoded = FastBeanCopier.copy(original, new LinkedHashMap()); + Assert.assertEquals(original.getClass().getName(), encoded.get("type")); + Assert.assertEquals(original.getMessage(), encoded.get("message")); + Assert.assertTrue(original.getClass().getName(), ((String) encoded.get("detail")).contains(original.toString())); + for (String key : Arrays.asList("cause", "suppressed", "stackTrace", "localizedMessage", "dangerous")) { + Assert.assertFalse(encoded.containsKey(key)); + } + if (original instanceof I18nSupportException) { + I18nSupportException i18n = (I18nSupportException) original; + Assert.assertEquals(i18n.getI18nCode(), encoded.get("i18nCode")); + Assert.assertArrayEquals(i18n.getArgs(), (Object[]) encoded.get("args")); + } + if (original instanceof BusinessException) { + BusinessException business = (BusinessException) original; + Assert.assertEquals(business.getCode(), encoded.get("code")); + Assert.assertEquals(business.getStatus(), encoded.get("status")); + } + Throwable restored = FastBeanCopier.copy(encoded, Throwable.class); + Assert.assertTrue(restored instanceof RemoteException); + Assert.assertEquals(original.getMessage(), restored.getMessage()); + Assert.assertEquals(0, restored.getStackTrace().length); + Assert.assertEquals(encoded.get("type"), ((RemoteExceptionMetadata) restored).getRemoteType()); + Assert.assertEquals(encoded.get("detail"), ((RemoteExceptionMetadata) restored).getRemoteDetail()); + Map forwarded = FastBeanCopier.copy(restored, new LinkedHashMap()); + Assert.assertEquals(encoded.keySet(), forwarded.keySet()); + encoded.forEach((key, value) -> Assert.assertTrue(key, Objects.deepEquals(value, forwarded.get(key)))); + Assert.assertSame(original, FastBeanCopier.copy(original, Throwable.class)); + Assert.assertSame(original, FastBeanCopier.DEFAULT_CONVERT.convert(original, original.getClass(), null)); + if (!original.getClass().isInstance(restored)) { + Assert.assertThrows(UnsupportedOperationException.class, () -> FastBeanCopier.copy(encoded, original.getClass())); + } + } + } + + public static class CustomException extends RuntimeException { + public CustomException(String message) { super(message); } + public String getDangerous() { throw new AssertionError("arbitrary getter must not run"); } + } + + public static class CustomI18nException extends I18nSupportException { + public CustomI18nException(String message, Object... args) { super(message, args); } + } + + public static class CustomBusinessException extends BusinessException { + public CustomBusinessException(String message, String code, int status, Object... args) { + super(message, code, status, args); + } + } +} From db2a17949ee40a324c47adbb25edbdc21f27aa55 Mon Sep 17 00:00:00 2001 From: zhou-hao Date: Fri, 27 Nov 2026 18:07:02 +0800 Subject: [PATCH 5/5] =?UTF-8?q?fix(exception):=20=E9=81=BF=E5=85=8D?= =?UTF-8?q?=E8=AF=8A=E6=96=AD=E8=BE=93=E5=87=BA=E5=9B=A0=E7=A9=BA=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E5=90=8D=E7=A7=B0=E8=A7=A6=E5=8F=91=E7=A9=BA=E6=8C=87?= =?UTF-8?q?=E9=92=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 异常显示名称为空时回退二进制类名,保留普通命名类及诊断格式。 覆盖匿名类、局部类、空名称扩展,以及匿名平台异常直接和嵌套转 Map。 --- hsweb-core/README.md | 4 ++ .../web/exception/TraceSourceException.java | 4 ++ .../exception/TraceSourceExceptionTest.java | 70 +++++++++++++++++++ 3 files changed, 78 insertions(+) diff --git a/hsweb-core/README.md b/hsweb-core/README.md index 0736bd216..9092eee05 100644 --- a/hsweb-core/README.md +++ b/hsweb-core/README.md @@ -45,6 +45,10 @@ ValidationException 的 details 以 property/message/detail 字段 Map 列表导 约定: 如果属性类实现了`Cloneable`接口,在复制的时候将调用`clone`方法.所以如果你实现了`Cloneable`接口,就必须重写`clone`方法并且为`public`修饰的. +### 异常诊断 + +`TraceSourceException.toString()` 在异常显示名称为空时(例如匿名类、局部类)回退到二进制类名,避免诊断和堆栈输出触发空指针;普通命名类继续使用原 canonical name,消息及 Operation/Source 格式保持不变。 + ### 数据字典 可通过枚举来定义数据字典,定义一个枚举,并实现`EnumDict`接口: diff --git a/hsweb-core/src/main/java/org/hswebframework/web/exception/TraceSourceException.java b/hsweb-core/src/main/java/org/hswebframework/web/exception/TraceSourceException.java index e87f1a85a..0e5f37fe4 100644 --- a/hsweb-core/src/main/java/org/hswebframework/web/exception/TraceSourceException.java +++ b/hsweb-core/src/main/java/org/hswebframework/web/exception/TraceSourceException.java @@ -181,6 +181,10 @@ protected String getExceptionName() { @Override public String toString() { String className = getExceptionName(); + // 匿名类、局部类的 canonical name 为空,使用二进制类名作为显示回退。 + if (className == null) { + className = getClass().getName(); + } String message = this.getLocalizedMessage(); String operation = this.operation; String source = Optional diff --git a/hsweb-core/src/test/java/org/hswebframework/web/exception/TraceSourceExceptionTest.java b/hsweb-core/src/test/java/org/hswebframework/web/exception/TraceSourceExceptionTest.java index b889e13c1..c718c8ffe 100644 --- a/hsweb-core/src/test/java/org/hswebframework/web/exception/TraceSourceExceptionTest.java +++ b/hsweb-core/src/test/java/org/hswebframework/web/exception/TraceSourceExceptionTest.java @@ -1,11 +1,81 @@ package org.hswebframework.web.exception; +import org.hswebframework.web.bean.FastBeanCopier; import org.junit.Test; +import java.util.LinkedHashMap; +import java.util.Map; + import static org.junit.Assert.*; public class TraceSourceExceptionTest { + @Test + public void anonymousAndLocalClassesUseBinaryNamesWhenCanonicalNamesAreAbsent() { + class LocalException extends TraceSourceException { + LocalException(String message) { super(message); } + } + for (TraceSourceException error : new TraceSourceException[]{ + new TraceSourceException() { }, new TraceSourceException("failed") { }, + new LocalException(null), new LocalException("failed")}) { + assertNull(error.getClass().getCanonicalName()); + String expected = error.getClass().getName(); + if (error.getMessage() != null) { + expected += ":" + error.getMessage(); + } + assertEquals(expected, error.toString()); + assertEquals(expected + "\n\t[Operation] ⇢ load\n\t [Source] ⇢ row", + error.withSource("load", "row").toString()); + } + } + + @Test + public void nullNameFromAnOverrideAlsoUsesTheBinaryClassName() { + NullNameException error = new NullNameException(); + assertNotNull(error.getClass().getCanonicalName()); + assertEquals(error.getClass().getName(), error.toString()); + } + + @Test + public void namedClassFormattingAndNullableSourceTextRemainCompatible() { + String name = TraceSourceException.class.getCanonicalName(); + assertEquals(name, new TraceSourceException().toString()); + assertEquals(name + ":", new TraceSourceException("").toString()); + assertEquals(name + ":failed\n\t[Operation] ⇢ load\n\t [Source] ⇢ row", + new TraceSourceException("failed").withSource("load", "row").toString()); + assertEquals(name, new TraceSourceException().withSource(new Object() { + @Override + public String toString() { return null; } + }).toString()); + } + + @Test + public void anonymousPlatformExceptionsCanExportDirectAndNestedDiagnostics() { + for (TraceSourceException error : new TraceSourceException[]{ + new I18nSupportException("trace.reason") { }, + new BusinessException("trace.reason", "BUSINESS") { }, + new ValidationException("trace.reason") { }}) { + error.withSource("load", "row"); + Map encoded = FastBeanCopier.copy(error, new LinkedHashMap<>()); + assertEquals(error.getClass().getName(), encoded.get("type")); + String detail = (String) encoded.get("detail"); + assertTrue(detail.contains(error.toString())); + assertTrue(detail.contains("[Operation] ⇢ load")); + assertTrue(detail.contains("[Source] ⇢ row")); + RuntimeException outer = new RuntimeException("outer", error); + outer.addSuppressed(error); + String nested = (String) FastBeanCopier.copy(outer, new LinkedHashMap<>()).get("detail"); + assertTrue(nested.contains(error.toString())); + assertTrue(nested.contains("Suppressed:")); + assertTrue(nested.contains("Caused by:")); + } + } + + public static class NullNameException extends TraceSourceException { + @Override + protected String getExceptionName() { return null; } + } + @Test public void test() {