簡體   English   中英

Windows Phone 8上未攔截System.Net.WebException

[英]System.Net.WebException not intercepted on Windows Phone 8

我正在嘗試使用RestSharp調用Web服務(必須從WP8開始進行此操作)。

這是我觸發的方法:

 private async void postRest()
 {
     string getSyncService = "MyService"; 
     var client = new RestClient(ip);
     var request = new RestRequest(getSyncService, Method.POST);              
     request.RequestFormat = DataFormat.Json;
     JsonObject jsonGenericRequest = new JsonObject();
     jsonGenericRequest.Add("companyid", "123");
     jsonGenericRequest.Add("token", "123");            ...
     request.AddParameter("GenMobileRequest", jsonGenericRequest);
     request.AddHeader("Access-Control-Allow-Methods", "POST");
     request.AddHeader("Content-Type", "application/json; charset=utf-8");
     request.AddHeader("Accept", "application/json");

     try
     {
         // easy async support
         client.ExecuteAsync(request, response =>
         {
             Console.WriteLine("response content: " + response.Content);
             if (response.ResponseStatus == ResponseStatus.Completed)
             {
                 MessageBox.Show("errorMsg: " + response.ErrorMessage);
             }
         });
     }
     catch (System.Net.WebException ex)
     {
         MessageBox.Show(" "  + ex.InnerException.ToString());
     }
 }

在我的日志中,我得到了這個異常:

System.Windows.ni.dll中發生了類型為'System.Net.WebException'的異常,在托管/本地邊界之前未進行處理

我什至無法在處理程序中保留任何信息

// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
    Console.WriteLine(" ---Application_UnhandledException---");
    if (Debugger.IsAttached)
    {
        // An unhandled exception has occurred; break into the debugger
        Debugger.Break();
    }
}

我如何獲得有關出了什么問題的更多信息?

有關調用WS的正確方法的任何其他信息,將不勝感激。

謝謝

原因是異步無效方法的異常無法捕獲。

異步void方法具有不同的錯誤處理語義。 從異步Task或異步Task方法拋出異常時,將捕獲該異常並將其放置在Task對象上。 使用異步void方法時,沒有Task對象,因此從異步void方法拋出的任何異常都將直接在啟動異步void方法時處於活動狀態的SynchronizationContext上引發

錯誤是異步void方法需要改為異步Task方法。

來源在此處此處的 msdn上

來源: https : //blogs.msdn.microsoft.com/ptorr/2014/12/10/async-exceptions-in-c/

  using System;
  using System.Runtime.CompilerServices;
  using System.Threading;
  using System.Threading.Tasks;

  namespace AsyncAndExceptions
  {
class Program
{
  static void Main(string[] args)
  {
    AppDomain.CurrentDomain.UnhandledException += (s, e) => Log("*** Crash! ***", "UnhandledException");
    TaskScheduler.UnobservedTaskException += (s, e) => Log("*** Crash! ***", "UnobservedTaskException");

    RunTests();

    // Let async tasks complete...
    Thread.Sleep(500);
    GC.Collect(3, GCCollectionMode.Forced, true);
  }

  private static async Task RunTests()
  {
    try
    {
      // crash
      // _1_VoidNoWait();

      // crash 
      // _2_AsyncVoidAwait();

      // OK
      // _3_AsyncVoidAwaitWithTry();

      // crash - no await
      // _4_TaskNoWait();

      // crash - no await
      // _5_TaskAwait();

      // OK
      // await _4_TaskNoWait();

      // OK
      // await _5_TaskAwait();
    }
    catch (Exception ex) { Log("Exception handled OK"); }

    // crash - no try
    // await _4_TaskNoWait();

    // crash - no try
    // await _5_TaskAwait();
  }

  // Unsafe
  static void _1_VoidNoWait()
  {
    ThrowAsync();
  }

  // Unsafe
  static async void _2_AsyncVoidAwait()
  {
    await ThrowAsync();
  }

  // Safe
  static async void _3_AsyncVoidAwaitWithTry()
  {
    try { await ThrowAsync(); }
    catch (Exception ex) { Log("Exception handled OK"); }
  }

  // Safe only if caller uses await (or Result) inside a try
  static Task _4_TaskNoWait()
  {
    return ThrowAsync();
  }

  // Safe only if caller uses await (or Result) inside a try
  static async Task _5_TaskAwait()
  {
    await ThrowAsync();
  }

  // Helper that sets an exception asnychronously
  static Task ThrowAsync()
  {
    TaskCompletionSource tcs = new TaskCompletionSource();
    ThreadPool.QueueUserWorkItem(_ => tcs.SetException(new Exception("ThrowAsync")));
    return tcs.Task;
  }
  internal static void Log(string message, [CallerMemberName] string caller = "")
  {
    Console.WriteLine("{0}: {1}", caller, message);
  }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM