我用 FaultExceptions 定义了一个 WCF 服务,但客户端没有正确捕获异常。
例外情况的合同是:
[DataContract]
public class ServiceFault {
[DataMember]
public string Operation { get; set; }
[DataMember]
public string Reason { get; set; }
[DataMember]
public string Message { get; set; }
}
操作
public interface IProductsService {
[OperationContract]
[FaultContract(typeof(ServiceFault))]
List<string> ListProducts();
}
在操作中我故意引入了一个错误:
public List<string> ListProducts() {
List<string> productsList = null;// = new List<string>();
try {
using (var database = new AdventureWorksEntities()) {
var products = from product in database.Products
select product.ProductNumber;
productsList.Clear(); // Introduced this error on purpose
productsList = products.ToList();
}
}
catch (Exception e) {
throw new FaultException<ServiceFault>(new ServiceFault() {
Operation = MethodBase.GetCurrentMethod().Name,
Reason = "Error ocurred",
Message = e.InnerException.Message
});
}
return productsList;
}
然后在客户端应用程序中,我抓住了
catch (FaultException<ServiceFault> ex) {
Console.WriteLine("FaultException<ArgumentFault>: {0} - {1} - {2}",
ex.Detail.Operation, ex.Detail.Reason, ex.Detail.Message);
}
catch (FaultException e) {
Console.WriteLine("{0}: {1}", e.Code.Name, e.Reason);
}
但是第二个捕获是捕获错误,所以我收到了这条消息(虽然正确的形式不正确)
InternalServiceFault: Object reference not set to an instance of an object
我该怎么做才能使强类型异常捕获错误?
PS:有一个类似的帖子,但我不明白