【问题标题】:Can't catch a FaultException<T> from the client application correctly无法从客户端应用程序正确捕获 FaultException<T>
【发布时间】:2014-03-30 22:37:25
【问题描述】:

我定义了一个带有 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:有一个类似的帖子,但我没看懂

【问题讨论】:

    标签: c# wcf nullreferenceexception faultexception


    【解决方案1】:

    您确定e.InnerExceptionMessage = e.InnerException.Message 中不为空吗?

    这将导致服务调用中出现未处理的NullReferenceException,从而抛出FaultException&lt;ExceptionDetail&gt; 而不是FaultException&lt;ServiceFault&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-24
      • 2018-06-22
      相关资源
      最近更新 更多