MapStruct中ValueMappings如何抛出自定义异常替代IllegalArgumentException?
在MapStruct中抛出自定义异常替代IllegalArgumentException
可以实现抛出CustomArgumentException,MapStruct自带的MappingConstants.THROW_EXCEPTION仅支持默认的IllegalArgumentException,需要通过自定义转换逻辑来实现需求,下面是两种可行方案:
方案一:自定义转换类+@Named注解
- 编写独立的转换类,手动处理字符串到枚举的映射逻辑,匹配失败时抛出自定义异常:
public class StatusConverter { @Named("stringToStatus") public Status stringToStatus(String statusStr) { return switch (statusStr) { case "ACTIVE" -> Status.A; case "INACTIVE" -> Status.I; default -> throw new CustomArgumentException("无效的状态值: " + statusStr); }; } }
- 在MapStruct映射接口中引入该转换类,并指定使用自定义转换方法:
@Mapper(uses = StatusConverter.class) public interface StatusMapper { // 直接调用自定义转换方法实现字符串转枚举 @Named("stringToStatus") Status stringToStatus(String statusStr); // 或者在实体映射中引用该方法 @Mapping(source = "statusStr", target = "status", qualifiedByName = "stringToStatus") TargetDto convertToDto(SourceEntity source); }
方案二:接口默认方法封装转换逻辑
在映射接口中添加默认方法,封装MapStruct自动生成的转换逻辑,匹配失败时抛出自定义异常:
@Mapper(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL) public interface StatusMapper { @ValueMappings({ @ValueMapping(source = "ACTIVE", target = "A"), @ValueMapping(source = "INACTIVE", target = "I") }) Status stringToStatus(String statusStr); default Status stringToStatusWithCustomException(String statusStr) { Status status = stringToStatus(statusStr); if (status == null) { throw new CustomArgumentException("无效的状态值: " + statusStr); } return status; } }
注意:需配置
nullValueMappingStrategy = RETURN_NULL,确保MapStruct在匹配不到枚举值时返回null,这样默认方法才能捕获到异常场景。
内容的提问来源于stack exchange,提问作者inquirymind
相关产品推荐
相关产品推荐

