2009-04-28 10 views
1

C# 2008C# Gestion des exceptions dans les classes

J'ai développé la classe ci-dessous. Je dois obtenir l'équilibre du serveur Web. Une fois cela fait, il rappellera dans mon application principale avec le résultat.

Cependant, parfois, le serveur Web échoue pour une raison inconnue. Pourrait être un volume élevé de trafic ou autre chose. Cependant, je n'ai pas implémenté de gestion des exceptions dans ma classe. Comme l'application qui utilise cela gère l'exception.

Cependant, le client a confirmé que lorsque le serveur Web échoue, il affiche une boîte de dialogue d'exception non gérée. Ensuite, ils doivent cliquer sur Continuer pour continuer à utiliser mon application. Donc, ci-dessous, je ne suis pas sûr si je devrais mettre en œuvre la gestion des exceptions dans ma classe. Cependant, je suis confus quant à savoir pourquoi l'exception n'a pas été interceptée dans mon application comme ci-dessous.

Un grand merci pour toutes les suggestions, ou si vous voyez quoi que ce soit d'autre mal,

private void OnGetBalanceCompleted(object sender, SIPPhoneLibraryEventArgs e) 
    { 
     try 
     { 
      //If the balance starts with 'null' there has been an error trying to get the balance. 
      if (e.Balance.StartsWith("null")) 
      { 
       statusDisplay1.CurrentBalance = CATWinSIP_MsgStrings.BalanceError; 
      } 
      else 
      { 
       // Display the current balance and round to 2 decimal places. 
       statusDisplay1.CurrentBalance = Math.Round(Convert.ToDecimal(e.Balance), 2).ToString(); 

       //If the balance is zero display in the status message 
       if (decimal.Parse(e.Balance) == 0) 
       { 
        this.statusDisplay1.CallStatus = "Zero Balance"; 
       } 
      } 
      //Remove the event as no longer needed 
      siplibrary.GetBalanceCompletedEvent -= new EventHandler<SIPPhoneLibraryEventArgs>(OnGetBalanceCompleted); 
     } 
     catch (WebException ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 




//Control library for all importing functions 
public class Balance : IDisposable 
{ 
    //Constructor 
    WebClient wc; 
    public Balance() 
    { 
     using (wc = new WebClient()) 
     { 
      //Create event handler for the progress changed and download completed events 
      wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged); 
      wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); 
     } 
    } 

    ~Balance() 
    { 
     this.Dispose(false); 
    } 

    //Event handler and the method that handlers the event 
    public EventHandler<SIPPhoneLibraryEventArgs> GetBalanceCompletedEvent; 

    //The method that raises the event 
    public void OnGetBalanceCompleted(SIPPhoneLibraryEventArgs e) 
    { 
     if (GetBalanceCompletedEvent != null) 
     { 
      GetBalanceCompletedEvent(this, e); 
     } 
    } 

    //Get the current balance for the user that is logged in. 
    //If the balance returned from the server is NULL display error to the user. 
    //Null could occur if the DB has been stopped or the server is down.  
    public void GetBalance(string sipUsername) 
    { 
     //Remove the underscore (_) from the username, as this is not needed to get the balance. 
     sipUsername = sipUsername.Remove(0, 1); 

     string strURL = string.Format("http://xxx.xxx.xx.xx:xx/voipbilling/servlet/advcomm.voipbilling.GetBalance?CustomerID={0}", sipUsername); 

     //Download only when the webclient is not busy. 
     if (!wc.IsBusy) 
     { 
      // Sleep for 1/2 second to give the server time to update the balance. 
      System.Threading.Thread.Sleep(500); 
      // Download the current balance. 
      wc.DownloadStringAsync(new Uri(strURL)); 
     } 
     else 
     { 
      System.Windows.Forms.MessageBox.Show("Busy please try again"); 
     } 
    } 

    //return and display the balance after the download has fully completed 
    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
    { 
     //Pass the result to the event handler 
     this.OnGetBalanceCompleted(new SIPPhoneLibraryEventArgs(e.Result)); 
    } 

    //Progress state of balance. 
    void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
    { 
     //Write the details to the screen. 
     Console.WriteLine(e.TotalBytesToReceive); 
     Console.WriteLine(e.BytesReceived); 
     Console.WriteLine(e.ProgressPercentage); 
    } 


    //Dispose of the balance object 
    public void Dispose() 
    { 
     Dispose(true); 

     GC.SuppressFinalize(this); 
    } 

    //Remove the event handlers 
    private bool isDisposed = false; 
    private void Dispose(bool disposing) 
    { 
     if (!this.isDisposed) 
     { 
      if (disposing) 
      { 
       wc.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged); 
       wc.DownloadStringCompleted -= new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); 

       wc.Dispose(); 
      }    
      isDisposed = true; 
     } 
    } 
} 

Répondre

2

Il semble que vous interceptez l'exception sur l'événement OnGetBalanceCompleted uniquement, plutôt que sur le processus d'extraction de la balance.

En cas d'erreur lors de la récupération, OnGetBalanceCompleted n'est même pas appelé, c'est pourquoi votre gestionnaire d'exceptions n'est pas appelé.

2
  1. Il y a plus d'informations à l'exception que de sa propriété Message. Vous jetez toutes ces informations en affichant uniquement la propriété Message. Utilisez ex.ToString() à la place.
  2. Le code que vous avez publié fait-il partie de l'interface utilisateur? Si ce n'est pas le cas, alors il n'a rien à savoir de l'interface utilisateur. En particulier, il ne doit pas utiliser MessageBox.Show.
  3. Je supprime toutes les fonctionnalités de l'interface utilisateur et déclenche plutôt un événement. L'appelant écouterait l'événement et ferait un travail d'interface utilisateur.