System.Net.WebException未在Windows Phone 8上截获

时间:2014-12-06 09:01:58

标签: c# windows-phone-8 restsharp

我正在尝试使用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.Net.WebException'的例外情况发生在   System.Windows.ni.dll并没有在托管/本机之前处理   边界

我甚至无法在我的处理程序中保留任何信息

// 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的方法的任何其他信息将不胜感激。

由于

2 个答案:

答案 0 :(得分:0)

原因是Async Void方法的异常无法通过Catch捕获。

  

Async void方法具有不同的错误处理语义。当一个   异常被抛出异步任务或异步任务方法,即   捕获异常并将其放在Task对象上。用async void   方法,没有Task对象,所以抛出任何异常   异步void方法将直接引发   在async void方法时处于活动状态的SynchronizationContext   开始

错误是需要将async void方法更改为异步Task方法。

来源位于msdn herehere

答案 1 :(得分:0)

来源: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);
  }
}

}