Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion hsweb-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,28 @@

实现位于 `hsweb-core/src/main/java/org/hswebframework/web/bean/FastBeanCopier.java`,使用独立的 `PropertyUtilsBean` 和内省扩展点,不修改全局 BeanUtils 配置,复用现有代码生成、类型转换和缓存。

访问器回归由 `FastBeanCopierBeanTest`、`FastBeanCopierReadOnlyTest` 和 `FastBeanCopierTest` 覆盖,包括只读源属性、目标可写边界、不同访问器风格、继承泛型、忽略属性、record、全局配置隔离及静态访问器排除。
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` 按名称取值。

直接将 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 用于错误描述,异常的真实类型还原不依赖类名反射实例化。

目标声明为 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 字段而主动恢复。

ValidationException 的 details 以 property/message/detail 字段 Map 列表导出,恢复时保留字段错误及详情;details 中的业务值保持浅复制。已知异常固定的业务 code/status 若与描述冲突会明确拒绝,不静默丢失。鉴权等上层模块的异常由其 SPI 实现扩展,hsweb-core 不反向依赖这些模块。

还原支持本地 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 返回值。

访问器回归由 `FastBeanCopierBeanTest`、`FastBeanCopierReadOnlyTest`、`FastBeanCopierReadOnceTest`、`FastBeanCopierTransientTest` 和 `FastBeanCopierTest` 覆盖,包括只读源属性、单次取值、导出排除规则、目标可写边界、不同访问器风格、继承泛型、忽略属性、record、全局配置隔离及静态访问器排除。`FastBeanCopierExceptionTest`、`FastBeanCopierExceptionRestoreTest`、`FastBeanCopierExceptionSpiTest` 及 `RemoteExceptionI18nTest` 覆盖异常描述、循环 cause、受控还原、JSON 往返、国际化回退和重译、值转换及双向 SPI 发现。

约定: 如果属性类实现了`Cloneable`接口,在复制的时候将调用`clone`方法.所以如果你实现了`Cloneable`接口,就必须重写`clone`方法并且为`public`修饰的.

### 异常诊断

`TraceSourceException.toString()` 在异常显示名称为空时(例如匿名类、局部类)回退到二进制类名,避免诊断和堆栈输出触发空指针;普通命名类继续使用原 canonical name,消息及 Operation/Source 格式保持不变。

### 数据字典

可通过枚举来定义数据字典,定义一个枚举,并实现`EnumDict`接口:
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String, Supplier<?>> 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<String, ?> source, Class<? extends Throwable> 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<Map<String, Object>> describeDetails(List<ValidationException.Detail> details) {
if (details == null) {
return null;
}
List<Map<String, Object>> result = new ArrayList<>(details.size());
for (ValidationException.Detail detail : details) {
Map<String, Object> 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<ValidationException.Detail> details(Object value) {
if (value == null) {
return null;
}
if (!(value instanceof List<?> list)) {
throw new IllegalArgumentException("Exception details must be a list");
}
List<ValidationException.Detail> 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();
}
}
Original file line number Diff line number Diff line change
@@ -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} 注册。
*
* <p>字段值必须延迟到 Supplier 被调用时读取,使 copier 能在读取前应用 include/ignore。
* copier 负责空值跳过和值转换;提供者不应提前生成堆栈等诊断信息。
* 自定义实现可继承 {@link DefaultExceptionConverter}。
*
* @see FastBeanCopier
*/
public interface ExceptionConverter {

void toMap(Throwable source, BiConsumer<String, Supplier<?>> properties);

/**
* 从异常描述恢复可赋值给目标声明的异常,不按远端 type 任意加载类。
* 不支持的目标或无效描述应明确抛错,不能返回 null 或不兼容的异常。
*/
Throwable fromMap(Map<String, ?> source, Class<? extends Throwable> targetType);
}
Loading
Loading