English 中文(简体)
Cannot Collection System.Net.WebException, 即使使用尝试渔获物
原标题:Cannot catch System.Net.WebException even though use try-catch
  • 时间:2023-12-16 16:51:02
  •  标签:
  • c#
  • maui

我有“网络MAUI”应用程序,Im试图检查与我网站链接:

private void CheckAPIConnection(string url)
{
    try
    {
        var request = WebRequest.CreateHttp(url);
        request.Method = "GET";

        HttpWebResponse response = null;

        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }
        catch (System.Net.WebException ex2)
        {
            DisplayAlert("Error", $"An unexpected error occurred: {ex2.Message}", "OK");
        }
        catch (Exception ex3)
        {
            // Handle other exceptions
            DisplayAlert("Error", $"An unexpected error occurred: {ex3.Message}", "OK");
        }
        
        if (response.StatusCode != HttpStatusCode.OK)
        {
            DisplayAlert("Error", 
                            $"Connection failed. This may caused by your internet connection " +
                            $"or our API are currently overloading or temporarily unavailable.

" +
                            $"Please check your internet connection, and if your internet connection " +
                            $"don t have any problems, you may need to wait for an hour and then try again " +
                            $"due to our API are currently overloading or temporarily unavailable.

" + 
                            $"Status code: {response.StatusCode}
Headers: {response.Headers}
" + 
                            $"Content Type: {response.ContentType}
Content Length: {response.ContentLength}
" + 
                            $"Last Modified: {response.LastModified}", "OK");
        }
    }
    catch (System.Net.WebException ex2)
    {
        DisplayAlert("Error", $"An unexpected error occurred: {ex2.Message}", "OK");
    }
    catch (Exception ex)
    {
        // Handle other exceptions
        DisplayAlert("Error", $"An unexpected error occurred: {ex.Message}", "OK");
    }
}

我用一个不知名的东道国来测试这一功能,以便检查所有工作:

CheckAPIConnection("https://lol.click/api/v1");

现在我有这个例外:

Exception has occurred: CLR/System.Net.WebException Exception thrown: System.Net.WebException in System.Net.Requests.dll: No such host is known. (lol.click:443) Inner exceptions found, see $exception in variables window for more details. Innermost exception System.Net.Sockets.SocketException : No such host is known. at System.Net.Dns.GetHostEntryOrAddressesCore(String hostName, Boolean justAddresses, AddressFamily addressFamily, Nullable1 startingTimestamp) at System.Net.Dns.GetHostAddresses(String hostNameOrAddress, AddressFamily family) at System.Net.Sockets.Socket.Connect(String host, Int32 port) at System.Net.Sockets.Socket.Connect(EndPoint remoteEP) at System.Net.HttpWebRequest.<>c__DisplayClass219_0.<<CreateHttpClient>b__1>d.MoveNext() at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.d__104.MoveNext()

我试图发布<>Continue,但我的方案在这一例外之后立即中断。 我的方案也在此例外之后立即终止。

这是例外情况的直观形象:

“entergraph

我无法抓住这一例外? 即便是Try-Schilling,这一例外也不可能被抓住,我感到很奇怪。

http://www.un.org。 我尝试了另一种做法,即使我试图赶上这一办法,这一例外仍然存在:

private async Task CheckAPIConnection(string url)
    {
        Thread.Sleep(10000);

        try
        {
            using (HttpClient client = new HttpClient())
            using (HttpResponseMessage response = await client.GetAsync(url))
            {
            
                if (!response.IsSuccessStatusCode)
                {
                    await DisplayAlert("Error", 
                                    $"Connection failed. This may caused by your internet connection " +
                                    $"or our API are currently overloading or temporarily unavailable.

" +
                                    $"Please check your internet connection, and if your internet connection " +
                                    $"don t have any problems, you may need to wait for an hour and then try again " +
                                    $"due to our API are currently overloading or temporarily unavailable.

" + 
                                    $"Status code: {response.StatusCode}
Content: {response.Content}
" + 
                                    $"Headers: {response.Headers}
Trailings Headers: {response.TrailingHeaders}
" + 
                                    $"Reason Phrase: {response.ReasonPhrase}", "OK");
                }
            }
        }
        catch (Exception ex)
        {
            // Handle other exceptions
            await DisplayAlert("Error", $"An unexpected error occurred: {ex.Message}", "OK");
        }
    }

例外:

using (HttpResponseMessage response = await client.GetAsync(url))

例外细节:

Exception has occurred: CLR/System.Net.Http.HttpRequestException Exception thrown: System.Net.Http.HttpRequestException in > System.Private.CoreLib.dll: No such host is known. (lol.click:443) Inner exceptions found, see $exception in variables window for more > details. Innermost exception System.Net.Sockets.SocketException : No such > host is known. at > System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(> SocketError error, CancellationToken cancellationToken) at > System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threadin> g.Tasks.Sources.IValueTaskSource.GetResult(Int16 token) at System.Net.Sockets.Socket.> <g__WaitForConnectWithCancellation|285_0>d.MoveNext() at System.Net.Http.HttpConnectionPool.> d__104.MoveNext()

这里是所要求的全部法典:

using Microsoft.Maui.Graphics;
using Microsoft.Maui.Controls;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace CyberCode;

public partial class SplashPage : ContentPage
{
    public SplashPage()
    {
        InitializeComponent();
    }

    /// <summary>
    /// Animation for application logo
    /// </summary>
    private async Task AnimationController()
    {
        imgSplashScreen.Opacity = 0;

        Thread.Sleep(3 * 1000);

        await imgSplashScreen.FadeTo(1, 1000);
    }

    private async Task CheckAPIConnection(string url)
    {
        Thread.Sleep(10000);

        try
        {
            using (HttpClient client = new HttpClient())
            using (HttpResponseMessage response = await client.GetAsync(url))
            {
            
                if (!response.IsSuccessStatusCode)
                {
                    await DisplayAlert("Error", 
                                    $"Connection failed. This may caused by your internet connection " +
                                    $"or our API are currently overloading or temporarily unavailable.

" +
                                    $"Please check your internet connection, and if your internet connection " +
                                    $"don t have any problems, you may need to wait for an hour and then try again " +
                                    $"due to our API are currently overloading or temporarily unavailable.

" + 
                                    $"Status code: {response.StatusCode}
Content: {response.Content}
" + 
                                    $"Headers: {response.Headers}
Trailings Headers: {response.TrailingHeaders}
" + 
                                    $"Reason Phrase: {response.ReasonPhrase}", "OK");
                }
            }
        }
        catch (Exception ex)
        {
            // Handle other exceptions
            await DisplayAlert("Error", $"An unexpected error occurred: {ex.Message}", "OK");
        }
    }

    /// <summary>
    /// Animation for ActivityIndicator
    /// </summary>
    private async Task AnimationActivityIndicator()
    {
        LoadingActivity.Opacity = 0;

        Thread.Sleep(5 * 1000);

        await LoadingActivity.FadeTo(1, 500);

        await CheckAPIConnection("https://lol.click/api/v1");
    }

    private async Task AnimationExitActivityIndicator() 
    {
        Thread.Sleep(20 * 1000);

        await LoadingActivity.FadeTo(0, 1000);
    }

    private async Task ShowLogInElements()
    {
        Thread.Sleep(10 * 1000);

        // Username
        Frame entryFrameUsername = new Frame
        {
            BorderColor = Color.FromHex("#C49B33"),
            CornerRadius = 10,
            Padding = new Thickness(2, 8),
            WidthRequest = 250,
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center,
            Opacity = 0 // Set initial opacity to 0 for the appearing animation
        };

        Entry txtUsername = new Entry
        {
            MaxLength = 255,
            BackgroundColor = Color.FromRgba(0, 0, 0, 0),
            TextColor = Color.FromHex("#FFFFFF"),
            PlaceholderColor = Color.FromHex("#a9a9a9"),
            Placeholder = "Username"
        };

        entryFrameUsername.Content = txtUsername;

        // Password

        Frame entryFramePassword = new Frame
        {
            BorderColor = Color.FromHex("#FFFFFF"),
            CornerRadius = 10,
            Padding = new Thickness(2, 0),
            WidthRequest = 255,
            HorizontalOptions = LayoutOptions.Center,
            Opacity = 0
        };
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        
        Task.Run(async () => await AnimationController());
        
        LoadingActivity.IsRunning = true;

        Task.Run(async () => await AnimationActivityIndicator());

        Task.Delay(TimeSpan.FromSeconds(10));

        Task.Run(async () => await AnimationExitActivityIndicator());
    }
}
问题回答

我找到了解决这一问题的办法。

这是因为:Thread.Sleep() 摧毁了一切,将其改为await 任务。

留待所有例外User-unhandled exceptionions,载于Breakpoints,然后重新启用申请

这是完整的C#代码:

using Microsoft.Maui.Graphics;
using Microsoft.Maui.Controls;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace CyberCode;

public partial class SplashPage : ContentPage
{
    public SplashPage()
    {
        InitializeComponent();
    }

    /// <summary>
    /// Animation for application logo
    /// </summary>
    private async Task AnimationController()
    {
        imgSplashScreen.Opacity = 0;

        await Task.Delay(3000);

        await imgSplashScreen.FadeTo(1, 1000);
    }

    private async Task CheckAPIConnection(string url)
    {
        await Task.Delay(10000);

        try
        {
            using (HttpClient client = new HttpClient())
            using (HttpResponseMessage response = await client.GetAsync(url))
            {
            
                if (!response.IsSuccessStatusCode)
                {
                    await DisplayAlert("Error", 
                                    $"Connection failed. This may caused by your internet connection " +
                                    $"or our API are currently overloading or temporarily unavailable.

" +
                                    $"Please check your internet connection, and if your internet connection " +
                                    $"don t have any problems, you may need to wait for an hour and then try again " +
                                    $"due to our API are currently overloading or temporarily unavailable.

" + 
                                    $"Status code: {response.StatusCode}
Content: {response.Content}
" + 
                                    $"Headers: {response.Headers}
Trailings Headers: {response.TrailingHeaders}
" + 
                                    $"Reason Phrase: {response.ReasonPhrase}", "OK");
                }
            }
        }
        catch (Exception ex)
        {
            // Handle other exceptions
            await DisplayAlert("Error", $"An unexpected error occurred: {ex.Message}", "OK");
        }
    }

    /// <summary>
    /// Animation for ActivityIndicator
    /// </summary>
    private async Task AnimationActivityIndicator()
    {
        LoadingActivity.Opacity = 0;

        await Task.Delay(5000);

        await LoadingActivity.FadeTo(1, 1000);

        await CheckAPIConnection("https://lol.click/");
    }

    private async Task AnimationExitActivityIndicator() 
    {
        await Task.Delay(15000);

        await LoadingActivity.FadeTo(0, 1500);
    }

    private async Task ShowLogInElements()
    {
        await Task.Delay(1000);

        // Username
        Frame entryFrameUsername = new Frame
        {
            BorderColor = Color.FromHex("#C49B33"),
            CornerRadius = 10,
            Padding = new Thickness(2, 8),
            WidthRequest = 250,
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center,
            Opacity = 0 // Set initial opacity to 0 for the appearing animation
        };

        Entry txtUsername = new Entry
        {
            MaxLength = 255,
            BackgroundColor = Color.FromRgba(0, 0, 0, 0),
            TextColor = Color.FromHex("#FFFFFF"),
            PlaceholderColor = Color.FromHex("#a9a9a9"),
            Placeholder = "Username"
        };

        entryFrameUsername.Content = txtUsername;

        // Password

        Frame entryFramePassword = new Frame
        {
            BorderColor = Color.FromHex("#FFFFFF"),
            CornerRadius = 10,
            Padding = new Thickness(2, 0),
            WidthRequest = 255,
            HorizontalOptions = LayoutOptions.Center,
            Opacity = 0
        };
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        
        await AnimationController();
        
        LoadingActivity.IsRunning = true;

        await AnimationActivityIndicator();

        await AnimationExitActivityIndicator();
    }
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...