【问题标题】:System.Net.WebException not intercepted on Windows Phone 8在 Windows Phone 8 上未拦截 System.Net.WebException
【发布时间】:2014-12-06 09:01:57
【问题描述】:

我正在尝试使用 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 的正确方法的额外信息将不胜感激。

谢谢

【问题讨论】:

  • 你在 lambda 中尝试过 try/catch 吗?
  • 是的,我做了,就像在代码中一样,但没有拦截任何东西......
  • 不,lambda 内部没有异常处理。你只有在调用 ExecuteAsync 时才有它。
  • 此链接很好地回答了您的问题并进行了解释。 blogs.msdn.microsoft.com/ptorr/2014/12/10/async-exceptions-in-c

标签: c# windows-phone-8 restsharp


【解决方案1】:

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

}

【讨论】:

    【解决方案2】:

    原因是 Async Void 方法的异常不能被 Catch 捕获。

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

    错误是async void方法需要改为async Task方法。

    来源在 msdn here 和 here

    【讨论】:

    • 这只是故事的一半。 async void 方法没有任何问题 if 异常是在方法本身内部处理的。另一方面,将方法转换为返回 Task<T> 将无济于事,除非有人在另一端 awaiting(或明确获取 Result) - 在 try/catch 中当然。
    • @PeterTorr,您能否提供第二种情况的示例?
    • 好的,添加了一些东西here
    猜你喜欢
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多