我有一個三輪架構的應用程序。我不明白如何在這種情況下處理異常。我收集了一些問題:多層架構中的異常處理最佳實踐
1。我是否需要創建一個通用異常,如PersistentException
,並使所有DAO類方法只拋出一種類型 - PersistentException
?即在每個DAO方法(CRUD)內部都這樣做:
public create(Entity instance) {
try {
...// all operations here
} catch(Exception e) {
throw new PersistentException(e);
}
}
2。每個 EJB服務創建一個的異常類是可以的(每個EJB接口有一個異常)?
I.e.假設我有一個EJB豆狀PersonManagementBean
,OrganizationManagementBean
,EmployeeManagementBean
相應@local
和@remote
接口。它們暴露給客戶,即事實上它們是會話外觀(所以它們位於服務層)。所以最好爲每個bean創建相應的Exception類(PersonManagementException
,OrganizationManagementException
,EmployeeManagementException
)?
或者最好是隻叫ServiceException
(如DAO中的情況下)一個例外?
3。哪種類型的例外可能會導致我的服務(繁忙)級別(,通常情況下爲)?我可以將DAO(PersistentException
)異常傳播給客戶嗎?即
public void relocatePerson() {
try {
Person p = personDao.getPerson(); // can throw PersistentException
....
if (someCondition) {
throw new PersonManagementException(); // throwing same PersonManagementException
}
....
} catch(PersonManagementException e) {
throw e; //don't need to rewrap same exception
} catch(PersistentException e) {
throw e; // DO I need to throw it as PersistentException to client? Or it's better to rewrap it as PersonManagementException?
} catch(Exception e) {
throw new PersonManagementException(e) //throwing all exception as service specific exception
}
}
或者我需要重新拋出所有異常(通常情況下)作爲特定於服務的異常?
- 「在通常情況下」我的意思是,我知道,在某些情況下,一些方法可以拋出其他例外有一些有用的信息(例如
ValidationException
與有關哪些對象沒有通過驗證規則)
好的,謝謝。但是,你能否更深入地解釋一下這個詞:「非常小心,不要用冗餘異常類來增加遠程接口的負擔。如果我的每個遠程方法都會被標記爲「拋出MyExecption」?什麼與它?什麼類型的異常必須由EJB拋出 - 檢查或未檢查的異常?謝謝 – MyTitle
您聲明的所有異常都必須包含在客戶端JAR依賴項中。如果他們沒有帶來商業價值,他們只是自重。由於所有的EJB異常都必須擴展'RemoteException',因此在checked和unchecked之間沒有選擇。 –
你確定嗎?我認爲擴展'RemoteException'並不是強有力的要求(至少在EJB 3.0中)。我有擴展'Exception'的經驗,而不是'RemoteException'。 – MyTitle