WCF/C# Unable to catch EndpointNotFoundException

前端 未结 5 1430
北荒
北荒 2021-01-07 23:09

I have created a WCF service and client and it all works until it comes to catching errors. Specifically I am trying to catch the EndpointNotFoundException for

5条回答
  •  Happy的楠姐
    2021-01-07 23:58

    Take a look at this post for details on this possible solution. The code shows use of a generate proxy but is valid on ChannelFactory and others as well.

    Typical here-be-dragons pattern

    using (WCFServiceClient c = new WCFServiceClient())
    {
        try
        {
            c.HelloWorld();
        }
        catch (Exception ex)
        {
            // You don't know it yet but your mellow has just been harshed.
    
            // If you handle this exception and fall through you will still be cheerfully greeted with 
            // an unhandled CommunicationObjectFaultedException when 'using' tries to .Close() the client.
    
            // If you throw or re-throw from here you will never see that exception, it is gone forever. 
            // buh bye.
            // All you will get is an unhandled CommunicationObjectFaultedException
        }
    } // <-- here is where the CommunicationObjectFaultedException is thrown
    

    Proper pattern:

    using (WCFServiceClient client = new WCFServiceClient())
    {
        try
        {
            client.ThrowException();
    
        }
        catch (Exception ex)
        {
            // acknowledge the Faulted state and allow transition to Closed
            client.Abort();
    
            // handle the exception or rethrow, makes no nevermind to me, my
            // yob is done ;-D
        }
    } 
    

    Or, as expressed in your question without a using statement,

    WCFServiceClient c = new WCFServiceClient();
    
    try
    {
        c.HelloWorld();
    }
    catch
    {
        // acknowledge the Faulted state and allow transition to Closed
        c.Abort();
    
        // handle or throw
        throw;
    }
    finally
    {
        c.Close();
    }
    

提交回复
热议问题