I keep getting WCF service is in faulted state on the client side. How should I catch WCF exceptions, without breaking my WCF service?

前端 未结 3 1861
故里飘歌
故里飘歌 2021-02-04 15:48

I have a WCF service multiple UIs consume. When the user is unable to access the database, I get Unauthorised exception from the DB. I don\'t catch the exception on the server

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 16:36

    You can use this code to create a wrapper class that will properly handle WCF exceptions:

    public class ServiceProxyHelper : IDisposable
        where TProxy : ClientBase, new()
        where TChannel : class
    {
        ///
        /// Private instance of the WCF service proxy.
        ///
        private TProxy _proxy;
    
        ///
        /// Gets the WCF service proxy wrapped by this instance.
        ///
        public TProxy Proxy
        {
            get
            {
                if (_proxy != null)
                {
                    return _proxy;
                }
                else
                {
                    throw new ObjectDisposedException("ServiceProxyHelper");
                }
            }
        }
    
        public TChannel Channel { get; private set; }
    
        ///
        /// Constructs an instance.
        ///
        public ServiceProxyHelper()
        {
            _proxy = new TProxy();
        }
    
        ///
        /// Disposes of this instance.
        ///
        public void Dispose()
        {
            try
            {
                if (_proxy != null)
                {
                    if (_proxy.State != CommunicationState.Faulted)
                    {
                        _proxy.Close();
                    }
                    else
                    {
                        _proxy.Abort();
                    }
                }
            }
            catch (CommunicationException)
            {
                _proxy.Abort();
            }
            catch (TimeoutException)
            {
                _proxy.Abort();
            }
            catch (Exception)
            {
                _proxy.Abort();
                throw;
            }
            finally
            {
                _proxy = null;
            }
        }
    }
    

    You can then call a service like this:

    using (ServiceProxyHelper svc =
       new ServiceProxyHelper())
    {
       svc.Proxy.SendMail(fromAddress, fromName, toEmail, toName, message);
    }
    

提交回复
热议问题