- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
尝试从 ASP.NET Core 3 SignalR Hub 捕获顶级异常
这很棘手,因为我使用的是 yield return,您不能将其包装在 try-catch block 中。它给出了这个编译器错误:
CS1626 C# Cannot yield a value in the body of a try block with a catch clause
那么,如何捕获这个异常呢?它被困在内部某处并发送到 javascript 客户端。我似乎看不到 ASP.NET Core 中间件管道中的异常。
// SignalR Hub
public class CrawlHub : Hub
{
public async IAsyncEnumerable<UIMessage> Crawl(string url, [EnumeratorCancellation]CancellationToken cancellationToken)
{
Log.Information("Here");
// Trying to catch this error further up pipeline as
// can't try catch here due to yield return
throw new HubException("This error will be sent to the client!");
// handing off to Crawler which returns back messages (UIMessage objects) every now and again on progress
await foreach (var uiMessage in Crawler.Crawl(url, cancellationToken))
{
// Check the cancellation token regularly so that the server will stop
// producing items if the client disconnects.
cancellationToken.ThrowIfCancellationRequested()
// update the stream UI with whatever is happening in static Crawl
yield return new UIMessage(uiMessage.Message, uiMessage.Hyperlink, uiMessage.NewLine);
}
}
}
try catch 异常以便 Log.Fatal(ex)
将其写入 serilog
正在将异常传递给 js 客户端。
2019-11-24 08:35:48.636 +00:00 [INF]
2019-11-24 08:35:48.682 +00:00 [INF] Starting up BLC.Website (Program.cs)
2019-11-24 08:35:48.917 +00:00 [INF] Development environment - using developer exception page
2019-11-24 08:35:48.995 +00:00 [INF] Application started. Press Ctrl+C to shut down.
2019-11-24 08:35:48.997 +00:00 [INF] Hosting environment: Development
2019-11-24 08:35:48.998 +00:00 [INF] Content root path: c:\dev\test\BrokenLink\BLC.Website
2019-11-24 08:35:49.138 +00:00 [INF] HTTP GET / responded 200 in 125.315 ms
2019-11-24 08:35:54.652 +00:00 [INF] HTTP GET /scan?urlToCrawl=davemateer.com responded 200 in 34.0029 ms
2019-11-24 08:35:54.820 +00:00 [INF] HTTP POST /crawlHub/negotiate responded 200 in 11.954 ms
2019-11-24 08:35:54.947 +00:00 [INF] Here
异常未被 ASP.NET Core 3 日志记录捕获。
程序.cs
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
//.MinimumLevel.Information() // this is the default
// Suppress framework log noise eg routing and handling
// so we'll see warnings and errors from the framework
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
try
{
Log.Information("");
Log.Information("Starting up BLC.Website (Program.cs)");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application start-up failed");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
// configuring logging for SignalR
.ConfigureLogging(logging =>
{
logging.AddFilter("Microsoft.AspNetCore.SignalR", LogLevel.Warning);
// turn on for connection debugging
//logging.AddFilter("Microsoft.AspNetCore.Http.Connections", LogLevel.Debug);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Startup.cs
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services, IWebHostEnvironment env)
{
services.AddRazorPages();
// send errors to the client
services.AddSignalR(options =>
{
if (env.IsDevelopment())
{
options.EnableDetailedErrors = true;
}
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
Log.Information("Development environment - using developer exception page");
app.UseDeveloperExceptionPage();
}
else
{
Log.Information("Non Development environment - errors go to /Error");
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
// don't want request logging for static files so put it here in the pipeline
app.UseSerilogRequestLogging();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapHub<CrawlHub>("/crawlHub");
});
}
最佳答案
这是我认为可行的答案:
// SignalR Hub
public class CrawlHub : Hub
{
// A wrapper iterator so can catch exceptions here which can't be done in
// a block which does yield return
public async IAsyncEnumerable<UIMessage> Crawl(string url, [EnumeratorCancellation] CancellationToken cancellationToken)
{
var enumerable = CrawlAndGetMessages(url, cancellationToken);
await using var enumerator = enumerable.GetAsyncEnumerator(cancellationToken);
for (var more = true; more;)
{
// Catch exceptions only on executing/resuming the iterator function
try
{
more = await enumerator.MoveNextAsync();
}
catch (Exception ex)
{
Log.Fatal("IteratorFunction() threw exception: " + ex);
throw;
}
// yield out this UIMessage this has to be outside a try catch block
yield return enumerator.Current;
}
}
public async IAsyncEnumerable<UIMessage> CrawlAndGetMessages(string url, [EnumeratorCancellation]CancellationToken cancellationToken)
{
// handing off to Crawler which returns back messages (UIMessage objects) every now and again on progress
await foreach (var uiMessage in Crawler.Crawl(url, cancellationToken))
{
// Check the cancellation token regularly so that the server will stop
// producing items if the client disconnects.
cancellationToken.ThrowIfCancellationRequested();
if (uiMessage.Message.Contains("404"))
// it should be displayed on the error list - this is not a stream
await Clients.Caller.SendAsync("ReceiveBrokenLinkMessage", "404 error on blah", cancellationToken);
else
// update the stream UI with whatever is happening in static Crawl
yield return new UIMessage(uiMessage.Message, uiMessage.Hyperlink, uiMessage.NewLine);
}
}
}
感谢@JeroenMostert 和@TheodorZoulias 在上面的评论和 Jackson Dunstan article .当我对此有更多了解时,我会发布改进。
关于c# - 在 SignalR ASP.NET Core 3.0 中尝试使用 IAsyncEnumerable Catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59020363/
我想知道是否可以安全地编写 catch() 来捕获所有 System.Exception 类型。或者我是否必须坚持使用 catch(Exception) 来完成此任务。我知道对于其他异常类型(例如 I
在 C# 中,'Catch'、'Catch (Exception)' 和 'Catch(Exception e)' 之间有什么区别? MSDN article on try-catch在其示例中使用了
然后一个 Promise 调用另一个 Promise,并且内部 Promise 从 catch .then block 中的外部 Promise 返回 我一般都在这里和谷歌上搜索过。尝试使用简单的 t
我们可以在 Try-Catch 中使用多个 catch 块。 但我的问题是:为什么可以使用单个 catch 块完成时使用多个 catch 块? 假设我想要我的问题的确切原因,我可以通过 Ex.mess
所以我在 service.ts 中有这个用户服务功能其中包括数据库的东西。 export const service = { async getAll(): Promise { try {
我不确定这里发生了什么。很明显为什么内扣会捕获throw 2 ,但为什么外面catch(int x)捕获 throw ?我以为catch(int x)应该只捕获整数值。第二个throw有可能吗?抛出什
我目前正在以不同的方式加载图像,如下所示: try { // way 1 } catch { // way 1 didn't work try { // way 2 }
这两者有什么区别?一个比另一个快吗?两者似乎都有效。有人请解释 没有 promise 的人: client.query(query1) .then(data => { callback(null
它几乎可以在所有语言中找到,而且我大部分时间都在使用它。 我不知道它是内部的,不知道它是如何真正起作用的。 它如何在任何语言的运行时在 native 级别工作? 例如:如果在 try 内部发生 sta
Closed. This question is opinion-based。它当前不接受答案。 想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。 1年前关闭。
我正在编写一个用于学习目的的短代码,要求用户输入密码才能登录 Facebook。我正在测试异常处理,由于某种原因,当密码错误时,Catch 部分没有执行。代码是: import java.util.S
如果try-catch的catch block 中抛出异常,那么finally block 会被调用吗? try { //some thing which throws error } cat
try { while ((inputLine = bufferedReader.readLine()) != null) { String[] words = inputLine.s
在 C# 上下文中,可以使用如下代码: try { ... } catch { ... } 在其他情况下,代码可以是: try { ... } catch (Exc
有时我在探索 ServiceStack 的代码库时遇到以下构造: try { ... } catch (Exception) { throw; } 在我看来,这种结构没有任何作用。这样做的
我最近遇到了一个 Javascript 问题,捕获错误,因此在抛出异常时崩溃。 funcReturnPromise().then().catch() 我必须将其更改为: try { funcRet
我在编写一些测试的 C++ 文件中遇到此错误: error: no member named 'Session' in namespace 'Catch' testResult = C
CException 是VC++抛出的所有异常的基类型,所以它应该捕获所有的异常吧? 最佳答案 CException 不是所有扩展的基类型(它可能是 MFC 代码使用的所有异常的基类型,但仅此而已)。
每次我看到 catch all 语句时: try { // some code } catch (...) { } 它一直是一种滥用。 反对使用 cache all 子句的论点是显而易见的。它会捕
代码相当简单——问题是 groupPath 字符串中有一个无效字符(准确地说是“/”)。 我正在尝试做的(至少作为权宜之计)是跳过我无法获得 cn 的 DirectoryEntries --- 不管为
我是一名优秀的程序员,十分优秀!