如何校验Java类指定成员变量非空并抛自定义异常避免DynamoDB入库?
实现必填字段校验并抛出自定义异常的方案
1. 定义自定义异常类
先创建一个业务异常类,用于标识必填字段缺失的场景:
public class MissingRequiredFieldException extends RuntimeException { public MissingRequiredFieldException(String message) { super(message); } }
2. 修改register方法添加校验逻辑
在构建数据库实体和执行保存操作之前,优先对type和url做非空校验,校验不通过直接抛出自定义异常,阻断后续入库操作:
public Registration register(RegistrationRequest registration) { // 校验必填字段:type不能为null或空白字符串 if (registration.getType() == null || registration.getType().trim().isEmpty()) { throw new MissingRequiredFieldException("type为必填字段,不能为null或空白"); } // 校验必填字段:url不能为null或空白字符串 if (registration.getUrl() == null || registration.getUrl().trim().isEmpty()) { throw new MissingRequiredFieldException("url为必填字段,不能为null或空白"); } // 校验通过后,继续构建数据库实体并执行保存 var dbEntry = RegistrationImpl.builder() .withType(registration.getType()) .withDescription(registration.getDescription()) .withUrl(registration.getUrl()) .withCategory(registration.getCategory()) .withMaxDuration(registration.getMaxDuration()) .build(); try { return repository.save(dbEntry); } catch (Exception e) { // 保留原有异常处理逻辑,比如日志记录或转抛其他异常 throw new RuntimeException("保存注册信息失败", e); } }
3. 可选调整说明
- 如果业务仅要求字段不为
null(允许空字符串),可以去掉trim().isEmpty()的判断,只保留== null的检查 - 如果需要强制调用方捕获异常,可将自定义异常改为受检异常(继承
Exception而非RuntimeException),同时在方法签名上添加throws MissingRequiredFieldException
内容的提问来源于stack exchange,提问作者kp1234
相关产品推荐
相关产品推荐

