我正在使用拋出 MessageException 和 IOException 的 smtp api
但是在我們的應用程式中,我們需要對兩者都有包裝例外。
是否可以為此撰寫包裝例外?像自定義例外?
uj5u.com熱心網友回復:
當然。例外只是,并且可以包裝任何東西;您不需要將它們寫成專門包裝 IOException 或 MessageExceptions。
public class MyCustomException extends Exception {
public MyCustomException(String msg) {
super(msg);
}
public MyCustomException(String msg, Throwable cause) {
super(msg, cause);
}
}
以上是所有自定義例外的樣子(在相關的情況下,它們可能有更多的欄位為特定故障注冊特定資訊,例如 SQLException 具有請求資料庫“錯誤代碼”的方法),但它們至少都有更多。
然后,包裝:
public void myMethod() throws MyException {
try {
stuffThatThrowsIOEx();
stuffThatThrowsMessageEx();
} catch (MessageException | IOException e) {
throw new MyException("Cannot send foo", e);
}
}
注意:您傳遞給您的字串MyException應該很短,不應使用大寫字母或感嘆號,或者在其末尾使用任何其他標點符號。此外,還要在其中包含實際的相關內容:例如,您嘗試為其發送訊息的用戶(重點是,您在其中包含的任何字串常量都需要簡單、簡短且不以標點符號結尾)。
uj5u.com熱心網友回復:
考慮創建一個根例外容器作為
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 Container 擴展您的 customException
public class CustomException extends GeneralExceptionContainer {
public MappingException(ExceptionCode exceptionCode) {
super(exceptionCode.name(), exceptionCode.getValue());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/442420.html
上一篇:模擬拋出受包保護的例外
