简体   繁体   English

如何在WCF中进行异常处理?

[英]How to do exception handling in wcf?

I have some questions: 我有一些疑问:

  1. does it need to use try catch in all layers of wcf service 是否需要在wcf服务的所有层中使用try catch
  2. I have simple layered wcf service: 我有简单的分层wcf服务:

and define: 并定义:

    [DataContract]
    public class ProductFault
    {
        public ProductFault(string msg)
        {
            FaultMessage = msg;
        }
        [DataMember]
        public string FaultMessage;
    }

and have: 并具有:

       public Product GetProduct(int id)
       {
           ProductBDO productBDO = null;
           try
           {
               productBDO = productLogic.GetProduct(id);
           }
           catch (Exception e)
           {
               string msg = e.Message;
               string reason = "GetProduct Exception";
               throw new FaultException<ProductFault>
               (new ProductFault(msg), reason);
           }
           if (productBDO == null)
           {
               string msg =
               string.Format("No product found for id {0}",
               id);
               string reason = "GetProduct Empty Product";
               throw new FaultException<ProductFault>(new ProductFault(msg), reason);
           }

           Product product = new Product();//****
           TranslateProductBDOToProductDTO(productBDO,
           product);
           return product;
       }

when I pass invalid id to 'GetProduct' method I receive this error message: 当我将无效的id传递给“ GetProduct”方法时,我收到此错误消息: 图片

How can I avoid raising error message in my service layer and send to client? 如何避免在服务层中引发错误消息并发送给客户端?

Do I need to use try catch in all layer of WCF service? 我需要在WCF服务的所有层中使用try catch吗?

No - you should only handle exceptions when you can do something about it (handle it, log it, etc.) 否-您应该只在可以做一些事情(处理,记录等)时处理异常。

How can avoid raising error message in my service layer and send to client? 如何避免在服务层中引发错误消息并发送给客户端?

What should you return if there is an exception? 如果有异常,您应该返回什么? How else would you let the client know that something unexpected has happened? 您还如何让客户知道发生了意外情况? Returning null for "product not found" seems appropriate but if there is a deeper problem I would think you'd want that exception to bubble up (or at the least log it) and let the client know that something bad has happened. 为“未找到产品”返回null似乎是适当的,但是如果存在更深的问题,我认为您希望该异常冒泡(或至少记录下来),并让客户端知道发生了什么不好的事情。 How much detail you want to allow to bubble up is up to you. 您要允许多少细节取决于您自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM