无法捕获异常

时间:2020-06-04 08:45:22

标签: c# .net exception signalr

这是我的代码:

        public async Task ConnectToHub()
        {
            try
            {
                hubConnection = new HubConnectionBuilder()
                                        .WithUrl(ApplicationConstants.ChutHubUrl)
                                        .Build();
                await hubConnection.StartAsync(); 
            }
            catch(Exception exception)
            {
                //I never enter this catch block (I set a breakpoint here 
                //but the debugger never breaks here).   
                //Instead, the app crashes and I get an unhandled HttpRequestException
            }
        }

在某个地方,hubConnection.StartAsync(失败时会抛出HttpRequestException。但是我似乎无法捕捉到此异常。我总是最终遇到未处理的HttpRequestException。

2 个答案:

答案 0 :(得分:0)

这很合逻辑,什么也看不到,因为正在运行的Web应用程序没有没有控制台。除了在额外的线程上运行它之外。

您正在asp.net上运行,没有控制台输出。

如果您想调试类似的内容,请使用Debug.WriteLine

Debug.WriteLine(exception.Message);

并使用诸如DebugView之类的程序读取结果

答案 1 :(得分:0)

我发现了我的问题所在。我在其他方法中还有另一个 await hubConnection.StartAsync(),它实际上是抛出HttpRequestException的方法,但是我没有创建catch块来捕获它。因此就是未处理的异常。