如何创建含特定字段的自定义异常?解决未捕获异常问题
问题解决方案
一、修复继承ProductsException的CustomException问题
1. 补充父类的必要方法和构造器
原ProductsException和MyError缺少getter方法,无法获取内部错误信息,同时ProductsException需要添加传入MyError的构造器:
@NoArgsConstructor public class ProductsException extends RuntimeException { private MyError error; public ProductsException(Exception e) { super(e); } // 添加构造器,用于传入自定义错误信息 public ProductsException(MyError error) { this.error = error; } // 添加getter获取内部错误对象 public MyError getError() { return error; } }
public class MyError { private final String errorCode; private final String message; private final String moreInfo; private final List<Errors> errors; public MyError(String errorCode, String message, String moreInfo, List<Errors> errors) { this.errorCode = errorCode; this.message = message; this.moreInfo = moreInfo; this.errors = errors; } // 添加getter暴露错误码和消息 public String getErrorCode() { return errorCode; } public String getMessage() { return message; } }
2. 修正CustomException的构造器与Builder
因为ProductsException是RuntimeException的子类,自定义异常继承它时必须显式调用父类构造器。结合Lombok的@Builder,需手动编写构造器确保调用父类构造:
@Builder public class CustomException extends ProductsException { private final String personId; private final String code; private final List<String> debugger; // 显式构造器,调用父类无参构造 public CustomException(String personId, String code, List<String> debugger) { super(); this.personId = personId; this.code = code; this.debugger = debugger; } // 可选:支持传递异常根源的构造器 public CustomException(String personId, String code, List<String> debugger, Throwable cause) { super((Exception) cause); this.personId = personId; this.code = code; this.debugger = debugger; } }
3. 修正控制器中的异常转换代码
修复错误信息的获取逻辑,同时补充personId的来源(需根据实际业务场景获取,比如请求参数、用户上下文):
catch(ProductsException e) { MyError error = e.getError(); // 处理error为空的边界情况 if (error == null) { throw CustomException.builder() .code("UNKNOWN_ERROR") .debugger(List.of("无可用错误详情")) .personId("默认ID") // 替换为实际逻辑 .build(); } throw CustomException.builder() .code(error.getErrorCode()) .debugger(List.of(error.getMessage())) .personId("1") // 替换为实际获取personId的逻辑 .build(); }
二、若CustomException改为继承RuntimeException的处理方式
如果直接继承RuntimeException,只需在构造器中把需要的字段传递给父类的构造器即可(父类支持传入消息、异常根源等参数):
@Builder public class CustomException extends RuntimeException { private final String personId; private final String code; private final List<String> debugger; // 将错误码作为异常消息传递给父类 public CustomException(String personId, String code, List<String> debugger) { super(code); this.personId = personId; this.code = code; this.debugger = debugger; } // 可选:同时传递异常根源 public CustomException(String personId, String code, List<String> debugger, Throwable cause) { super(code, cause); this.personId = personId; this.code = code; this.debugger = debugger; } }
此时控制器中的转换逻辑无需大改,只需确保CustomException的Builder能正确调用对应的构造器即可。
内容的提问来源于stack exchange,提问作者newLearner
相关产品推荐
相关产品推荐

