我正在使用 smtp api,它会抛出 MessageException 和 IOException
但在我们的应用程序中,我们需要两者都有包装异常。
是否可以为此编写包装异常?喜欢自定义异常吗?
当然。异常就是这样,并且可以包含任何东西;您不需要将它们编写为仅专门包装 IOException 或 MessageExceptions。
public class MyCustomException extends Exception {
public MyCustomException(String msg) {
super(msg);
}
public MyCustomException(String msg, Throwable cause) {
super(msg, cause);
}
}
上面是all自定义异常的样子(在相关的情况下,它们可能还有更多字段来注册特定故障的特定信息,例如 SQLException 有方法来询问数据库“错误代码”),但它们都在至少有以上。
然后,换行:
public void myMethod() throws MyException {
try {
stuffThatThrowsIOEx();
stuffThatThrowsMessageEx();
} catch (MessageException | IOException e) {
throw new MyException("Cannot send foo", e);
}
}
注意:传递给
MyException
的字符串应该很短,不应使用大写字母或感叹号,也不应在其末尾使用任何其他标点符号。此外,还应在其中包含实际的相关内容:例如,您尝试向其发送消息的用户(重点是,您在其中作为字符串常量包含的任何内容都必须简单、简短且不以标点符号结尾)。
考虑创建一个根异常容器:
public class GeneralExceptionContainer extends RuntimeException{
private Integer exceptionCode;
private String message;
public GeneralExceptionContainer(String argMessage, Integer exceptionCode) {
super(argMessage);
this.exceptionCode = exceptionCode;
this.message = argMessage;
}
public GeneralExceptionContainer(Throwable cause, Integer exceptionCode, String argMessage) {
super(argMessage, cause);
this.exceptionCode = exceptionCode;
this.message = argMessage;
}
}
对于一些枚举或序列化要求,您也可以添加
exceptionCode
:
public enum ExceptionCode {
SECTION_LOCKED(-0),
MAPPING_EXCEPTION(-110)
private final int value;
public int getValue() {
return this.value;
}
ExceptionCode(int value) {
this.value = value;
}
public static ExceptionCode findByName(String name) {
for (ExceptionCode v : values()) {
if (v.name().equals(name)) {
return v;
}
}
return null;
}
}
然后从根 GeneralException 容器扩展您的
customException
:
public class CustomException extends GeneralExceptionContainer {
public MappingException(ExceptionCode exceptionCode) {
super(exceptionCode.name(), exceptionCode.getValue());
}
}