我有興趣爲我的WCF應用程序實現適當的異常處理。在谷歌快速搭車後,我遇到了兩種解決方案。處理WCF異常/故障以及FaultException和IErrorHandler
- 爲客戶提供
FaultExceptions
。 - 使用
IErrorHandler
的一般異常處理。
我沒發現什麼,雖然是結合了這兩種方法的實際例子 - 如果這甚至認爲是很好的做法。
我的想法:
投擲FaultExceptions用自己的詳細類型
throw new FaultException<StackOverflowFault>(
new StackOverflowFault(StackOverflowFaultCode.Rules,
"This question is not considered as constructive."));
與IErrorHandler
捕獲未處理的異常,並記錄它們。基於異常的類型
public bool HandleError(Exception ex) {
try {
SomeLogger.Error(ex.Message, ex.Source);
return true;
} catch (Exception) {
// Well, there was an exception handling the
// exception :(
// -> Drop the exception and throw a new one
throw new Exception("Unknown exception occured.");
}
}
......並提供故障(不是一切爲了客戶的眼睛!)
public void ProvideFault(Exception error, MessageVersion version, ref Message fault){
if(error is FaultException) {
fault = Message.CreateMessage(version, ((FaultException<StackOverflowFault>)error).Reason)
} else if(error is SqlException) {
// What would Jon Skeet do?
}
}
我的問題
這是否被認爲是好的做法?並且:如果我已經在適用於客戶端的應用程序中拋出FaultException - 是否有意義讓它們由IErrorHandler
(自動執行)處理?
+1在您的問題中引用Skeet先生! – STLDeveloper