2017-06-23 1 views
0

Je suis relativement nouveau en programmation. J'ai besoin de gestion des exceptions pour mon HttpWebRequest à un Api. Ci-dessous est mon code, je n'ai pas fait de gestion des erreurs avant donc juste un exemple de la façon d'accomplir cela sera apprécié.C# Gestion des erreurs pour HttpWebRequest

private void button1_Click(object sender, EventArgs e) 
    { 
     Class1.PostDevices x = new Class1.PostDevices(); 

     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr); 
     request.ContentType = "application/json"; 
     request.Method = "POST"; 
     request.Timeout = 5000; 

     using (var streamWriter = new StreamWriter(request.GetRequestStream())) 
     { 
      string jsonstring; 
      MemoryStream stream1 = new MemoryStream(); 
      DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices)); 

      x.notification = new Class1.Notification(); 
      x.profile = "dev"; 
      x.notification.message = "Hello World"; 

      ser.WriteObject(stream1, x); 
      stream1.Position = 0; 
      StreamReader sr = new StreamReader(stream1); 

      jsonstring = sr.ReadToEnd(); 
      Debug.WriteLine(JObject.Parse(jsonstring)); 

      streamWriter.Write(jsonstring); 
      streamWriter.Flush(); 
     } 
     HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse(); 
     if (httpResponse.StatusCode == HttpStatusCode.OK) 
     { 
      using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
      { 
       string result = streamReader.ReadToEnd(); 
       Debug.WriteLine(JObject.Parse(result)); 
       Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result); 
      } 
     } 
    } 
} 
+0

Définir vos codes à l'intérieur 'catch try {} (exception Objex)' bloc et LOGGUE. pour la journalisation, vous pouvez créer votre enregistreur d'exception personnalisé pour stocker dans un fichier ou vous pouvez également utiliser une bibliothèque tierce comme Log4Net ... etc. –

+0

est votre application actuelle est une application web asp.net? –

+0

oui c'est. Pouvez-vous s'il vous plaît me montrer comment le faire –

Répondre

0

1) Créez un dossier nommé "ExceptionTextFile" dans votre application

2) créer une classe séparée comme ci-dessous pour enregistrer l'exception

using System; 
using System.IO; 
using context = System.Web.HttpContext; 

//Define your application namespace here 
namespace YourApplicationNamespace 
{ 
    public static class ExceptionLogging 
    { 
     private static String ErrorlineNo, Errormsg, extype, exurl, ErrorLocation; 

     public static void SendErrorToText(Exception ex) 
     { 
      var line = Environment.NewLine + Environment.NewLine; 

      ErrorlineNo = ex.StackTrace.ToString(); 
      Errormsg = ex.Message; 
      extype = ex.GetType().ToString(); 
      exurl = context.Current.Request.Url.ToString(); 
      ErrorLocation = ex.Message.ToString(); 
      try 
      { 
       //Create a folder named as "ExceptionTextFile" inside your application 
       //Text File Path 
       string filepath = context.Current.Server.MapPath("~/ExceptionTextFile/"); 
       if (!Directory.Exists(filepath)) 
       { 
        Directory.CreateDirectory(filepath); 
       } 
       //Text File Name 
       filepath = filepath + DateTime.Today.ToString("dd-MM-yy") + ".txt"; 
       if (!File.Exists(filepath)) 
       { 
        File.Create(filepath).Dispose(); 
       } 
       using (StreamWriter sw = File.AppendText(filepath)) 
       { 
        string error = "Log Written Date:" + " " + DateTime.Now.ToString() 
        + line + "Error Line No :" + " " + ErrorlineNo + line 
        + "Error Message:" + " " + Errormsg + line + "Exception Type:" + " " 
        + extype + line + "Error Location :" + " " + ErrorLocation + line 
        + " Error Page Url:" + " " + exurl + line + line; 
        sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------"); 
        sw.WriteLine("-------------------------------------------------------------------------------------"); 
        sw.WriteLine(line); 
        sw.WriteLine(error); 
        sw.WriteLine("--------------------------------*End*------------------------------------------"); 
        sw.WriteLine(line); 
        sw.Flush(); 
        sw.Close(); 
       } 
      } 
      catch (Exception e) 
      { 
       e.ToString(); 
      } 
     } 
    } 
} 

Après que l'intérieur de votre bouton click event define try ... attrape le bloc et enregistre l'exception comme ci-dessous

private void button1_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     Class1.PostDevices x = new Class1.PostDevices(); 

     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr); 
     request.ContentType = "application/json"; 
     request.Method = "POST"; 
     request.Timeout = 5000; 

     using (var streamWriter = new StreamWriter(request.GetRequestStream())) 
     { 
      string jsonstring; 
      MemoryStream stream1 = new MemoryStream(); 
      DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices)); 

      x.notification = new Class1.Notification(); 
      x.profile = "dev"; 
      x.notification.message = "Hello World"; 

      ser.WriteObject(stream1, x); 
      stream1.Position = 0; 
      StreamReader sr = new StreamReader(stream1); 

      jsonstring = sr.ReadToEnd(); 
      Debug.WriteLine(JObject.Parse(jsonstring)); 

      streamWriter.Write(jsonstring); 
      streamWriter.Flush(); 
     } 
     HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse(); 
     if (httpResponse.StatusCode == HttpStatusCode.OK) 
     { 
      using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
      { 
       string result = streamReader.ReadToEnd(); 
       Debug.WriteLine(JObject.Parse(result)); 
       Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result); 
      } 
     } 
    } 
    } 
    catch (Exception e) 
    { 
    ExceptionLogging.SendErrorToText(e);     
    } 
} 

Si une erreur apparaît, accédez au dossier "ExceptionTextFile" et vérifiez le journal. L'exception serait enregistrée ici.

essayer de me revenir si cela résout votre problème ou non

+0

Merci! Vous l'avez au travail –

+0

Vous êtes les bienvenus :) –