What exception handling should I choose to connect the client

I have a client class that connects to the server through WebRequest. Now I'm struggling with the best way to implement processing WebException. For good user interface feedback, I need (for now) an exception message and status.

I came up with three different approaches. The first just redraws the exception and I am processing the call method. This may be the most universal solution:

public class ClientSimpleRethrow
{
    public bool IsConnected { get; set; }

    public void Connect()
    {
        try
        {
            // do connection
        }
        catch (WebException)
        {
            IsConnected = false;
            throw;
        }

        IsConnected = true;
    }
}

The second version throws a custom exception with WebExceptionas an internal exception. This gives me the advantage of just catching and processing exactly what I expect. For example, there may be another error that also throws WebExceptionthat I would like to handle differently. So far this is my favorite solution:

public class ClientThrowCustom
{
    public bool IsConnected { get; set; }

    public void Connect()
    {
        try
        {
            // do connection
        }
        catch (WebException ex)
        {
            IsConnected = false;
            throw new ClientConnectionException(ex.Message, ex);
        }

        IsConnected = true;
    }
}

, . , , . , - , IsConnected. .

public class ClientProperties
{
    public bool IsConnected { get; set; }
    public string ConnectionErrorMessage { get; set; }
    public WebExceptionStatus? ConnectionErrorStatus { get; set; }

    public void Connect()
    {
        try
        {
            // do connection
        }
        catch (WebException ex)
        {
            IsConnected = false;
            ConnectionErrorMessage = ex.Message;
            ConnectionErrorStatus = ex.Status;
            return;
        }

        IsConnected = true;
        ConnectionErrorMessage = null;
        ConnectionErrorStatus = null;
    }
}

, . , , , - , .

!

+3
1

-, , . - . try , . .

, . :

  • Exception, - , API. WebException API, , - , LogInException .

  • MyApplicationException . API MyApplicationException . , API , , - , , . , .

+2

Source: https://habr.com/ru/post/1786391/


All Articles