httpClient.getAsync异常会绕过Try / Catch Block

时间:2018-02-16 21:30:57

标签: c# exception-handling async-await

我正在尝试运行等待的远程Web服务的异步连接。 URL是可配置的,如果它是无效的,我会得到一个Null Reference异常,忽略Try / Catch块并崩溃整个IIS Worker进程。

public static void SendMessage(FileInfo FileToSend, string RecipientName, string RecipientNumber){
{
    //Connection Info retrieved from DB
    string url = "http://NotARealUrl.com/";
    string username = "NotARealUN";
    string password = "NotARealPW";

    //not Awaiting this because all logging in event of job failure is handled by the job itself. There is no reason to wait for completion
    Send (FileToSend, url, username, password, RecipientName, RecipientNumber)
}

public static async Task Send(FileInfo FileToSend, string url, string username, string password, string sentByID, string faxRecipient, string faxNumber)
{
    var handler = new HttpClientHandler
    {
        Credentials = new NetworkCredential(username, password), 
        PreAuthenticate = true
    };

    var client = new HttpClient(handler);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    try
    {
        var response = await client.GetAsync(url); //Exception is throw when I step past this point
        response.EnsureSuccessStatusCode();

        var contentAsString = await response.Content.ReadAsStringAsync();
        var root = JsonConvert.DeserializeObject<FaxingAPIRoot>(contentAsString);

        //Code continues, using 'root' in order to send the message in accordance with the Faxing API I'm using
    }
    catch (Exception e)
    {
        //Graceful Error Handling 
    }
}

在上面指定的行......

var response = await client.GetAsync(url);

代码抛出以下异常,绕过Catch块并立即崩溃主机进程,无论是Visual Studio的IIS Express还是IIS Worker Process。

  

类型'System.NullReferenceException'的未处理异常   发生在mscorlib.dll

     

附加信息:对象引用未设置为的实例   对象

使用Callstack ......

    mscorlib.dll!System.Threading.Tasks.AwaitTaskContinuation.ThrowAsyncIfNecessary.AnonymousMethod__18_0(object s) 
    mscorlib.dll!System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(object state)  
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   
    mscorlib.dll!System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()  
    mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch()    
    mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() 
    [Native to Managed Transition]  

我已经验证传入的URL不为null且HttpClient不为null。有没有办法强制捕获此异常,或者禁止通过在尝试调用该URL之前检查该URL的有效性来抢占错误?

0 个答案:

没有答案