我使用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:有一个类似的帖子,但我不理解答案 0 :(得分:1)
您确定e.InnerException
中的Message = e.InnerException.Message
不为空吗?
这会导致服务电话中未处理的NullReferenceException
,从而导致FaultException<ExceptionDetail>
而不是FaultException<ServiceFault>
。