Skip to content

Commit f69a63d

Browse files
committed
feat: Catch a WebSocketException and convert to a warning
Client disconnections are normal - always log them as warnings, not errors
1 parent da7900b commit f69a63d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/VirtoCommerce.Xapi.Core/Extensions/ApplicationBuilderExtensions.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
using System;
2+
using System.Net.WebSockets;
23
using GraphQL.Server.Transports.AspNetCore;
34
using GraphQL.Server.Transports.AspNetCore.WebSockets;
45
using GraphQL.Server.Ui.GraphiQL;
56
using GraphQL.Types;
67
using Microsoft.AspNetCore.Builder;
78
using Microsoft.Extensions.DependencyInjection;
9+
using Microsoft.Extensions.Logging;
810
using Microsoft.Extensions.Options;
911
using VirtoCommerce.Xapi.Core.Infrastructure;
1012
using VirtoCommerce.Xapi.Core.Models;
@@ -24,6 +26,32 @@ public static IApplicationBuilder UseScopedSchema<TMarker>(this IApplicationBuil
2426
public static IApplicationBuilder UseSchemaGraphQL<TSchema>(this IApplicationBuilder builder, bool schemaIntrospectionEnabled = true, string schemaPath = null)
2527
where TSchema : ISchema
2628
{
29+
var loggerFactory = builder.ApplicationServices.GetRequiredService<ILoggerFactory>();
30+
var logger = loggerFactory.CreateLogger("GraphQLWebSocket");
31+
32+
builder.Use(async (_, next) =>
33+
{
34+
try
35+
{
36+
await next();
37+
}
38+
catch (WebSocketException wsEx) when (
39+
wsEx.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely ||
40+
wsEx.WebSocketErrorCode == WebSocketError.InvalidState)
41+
{
42+
// These are common and expected during client disconnects
43+
logger.LogWarning(
44+
"WebSocket disconnected: {ErrorCode} - {Message}",
45+
wsEx.WebSocketErrorCode,
46+
wsEx.Message);
47+
}
48+
catch (WebSocketException wsEx)
49+
{
50+
// Other WebSocket errors might need attention
51+
logger.LogWarning(wsEx, "WebSocket error occurred");
52+
}
53+
});
54+
2755
var graphQlPath = string.IsNullOrEmpty(schemaPath)
2856
? GraphQlPath
2957
: $"{GraphQlPath}/{schemaPath}";

0 commit comments

Comments
 (0)