Skip to content

Commit 18f7269

Browse files
authored
Improved error handling (#1714)
1 parent 664f9e7 commit 18f7269

File tree

11 files changed

+171
-83
lines changed

11 files changed

+171
-83
lines changed

samples/GraphQL.Samples.Http/Program.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
using System.Runtime.CompilerServices;
2+
3+
using Microsoft.AspNetCore.Mvc;
4+
25
using Tanka.GraphQL.Executable;
36
using Tanka.GraphQL.Server;
47

@@ -59,7 +62,7 @@
5962
app.Run();
6063

6164
// simple subscription generating numbers from 0 to the given number
62-
static async IAsyncEnumerable<int> Count(int to, [EnumeratorCancellation] CancellationToken cancellationToken)
65+
static async IAsyncEnumerable<int> Count(int to, [FromServices]ILogger<Program> logger, [EnumeratorCancellation] CancellationToken cancellationToken)
6366
{
6467
var i = 0;
6568
while (!cancellationToken.IsCancellationRequested)

src/GraphQL.Server/WebSockets/ServerMethods.cs

Lines changed: 40 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using System.Collections.Concurrent;
22

33
using Microsoft.AspNetCore.Http;
4+
5+
using Tanka.GraphQL.Fields;
46
using Tanka.GraphQL.Server.WebSockets.WebSocketPipe;
57
using Tanka.GraphQL.Validation;
68

@@ -56,40 +58,32 @@ await Channel.Complete(
5658
private async Task Execute(Subscribe subscribe, CancellationTokenSource unsubscribeOrAborted)
5759
{
5860
var cancellationToken = unsubscribeOrAborted.Token;
61+
var context = new GraphQLRequestContext
62+
{
63+
HttpContext = _httpContext,
64+
RequestServices = _httpContext.RequestServices,
65+
Request = new()
66+
{
67+
InitialValue = null,
68+
Document = subscribe.Payload.Query,
69+
OperationName = subscribe.Payload.OperationName,
70+
Variables = subscribe.Payload.Variables
71+
}
72+
};
5973

6074
try
6175
{
62-
var context = new GraphQLRequestContext
63-
{
64-
HttpContext = _httpContext,
65-
RequestServices = _httpContext.RequestServices,
66-
Request = new()
67-
{
68-
InitialValue = null,
69-
Document = subscribe.Payload.Query,
70-
OperationName = subscribe.Payload.OperationName,
71-
Variables = subscribe.Payload.Variables
72-
}
73-
};
74-
7576
await _requestDelegate(context);
7677
await using var enumerator = context.Response.GetAsyncEnumerator(cancellationToken);
7778

7879
while (await enumerator.MoveNextAsync())
7980
{
80-
await Client.Next(new Next()
81-
{
82-
Id = subscribe.Id,
83-
Payload = enumerator.Current
84-
}, cancellationToken);
81+
await Client.Next(new Next() { Id = subscribe.Id, Payload = enumerator.Current }, cancellationToken);
8582
}
8683

8784
if (!cancellationToken.IsCancellationRequested)
8885
{
89-
await Client.Complete(new Complete()
90-
{
91-
Id = subscribe.Id
92-
}, cancellationToken);
86+
await Client.Complete(new Complete() { Id = subscribe.Id }, cancellationToken);
9387
}
9488
}
9589
catch (OperationCanceledException)
@@ -99,26 +93,36 @@ await Client.Complete(new Complete()
9993
catch (ValidationException x)
10094
{
10195
var validationResult = x.Result;
102-
await Client.Error(new Error()
103-
{
104-
Id = subscribe.Id,
105-
Payload = validationResult.Errors.Select(ve => ve.ToError()).ToArray()
106-
}, cancellationToken);
96+
await Client.Error(
97+
new Error()
98+
{
99+
Id = subscribe.Id,
100+
Payload = validationResult.Errors.Select(ve => ve.ToError()).ToArray()
101+
}, cancellationToken);
107102
}
108103
catch (QueryException x)
109104
{
110-
await Client.Error(new Error()
111-
{
112-
Id = subscribe.Id,
113-
Payload = new[]
105+
await Client.Error(
106+
new Error()
107+
{
108+
Id = subscribe.Id,
109+
Payload = new[]
110+
{
111+
context.Errors?.FormatError(x)!
112+
}
113+
}, cancellationToken);
114+
}
115+
catch (Exception x)
116+
{
117+
await Client.Error(
118+
new Error()
114119
{
115-
new ExecutionError()
120+
Id = subscribe.Id,
121+
Payload = new[]
116122
{
117-
Path = x.Path.Segments.ToArray(),
118-
Message = x.Message
123+
context.Errors?.FormatError(x)!
119124
}
120-
}
121-
}, cancellationToken);
125+
}, cancellationToken);
122126
}
123127
finally
124128
{

src/GraphQL/ErrorCollectorFeature.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ public IEnumerable<ExecutionError> GetErrors()
1818
return _bag.Select(DefaultFormatError);
1919
}
2020

21+
public ExecutionError FormatError(Exception x)
22+
{
23+
return DefaultFormatError(x);
24+
}
25+
2126
public ExecutionError DefaultFormatError(Exception exception)
2227
{
2328
var rootCause = exception.GetBaseException();

src/GraphQL/ExceptionExtensions.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
using Tanka.GraphQL.Fields;
2-
using Tanka.GraphQL.Language.Nodes;
1+
using Tanka.GraphQL.Language.Nodes;
32
using Tanka.GraphQL.Language.Nodes.TypeSystem;
43
using Tanka.GraphQL.ValueResolution;
54

src/GraphQL/ExecutionError.cs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public class ExecutionError
1111

1212
[JsonPropertyName("locations")]
1313
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
14-
public List<Location>? Locations { get; set; }
14+
public List<SerializedLocation>? Locations { get; set; }
1515

1616
[JsonPropertyName("message")] public string Message { get; set; } = string.Empty;
1717

@@ -23,4 +23,28 @@ public void Extend(string key, object value)
2323

2424
Extensions[key] = value;
2525
}
26+
}
27+
28+
public class SerializedLocation
29+
{
30+
public int Line { get; set; }
31+
32+
public int Column { get; set; }
33+
34+
public static implicit operator SerializedLocation(Location location)
35+
{
36+
return new()
37+
{
38+
Line = location.Line,
39+
Column = location.Column
40+
};
41+
}
42+
}
43+
44+
public static class ExecutionErrorExtensions
45+
{
46+
public static List<SerializedLocation> ToSerializedLocations(this IEnumerable<Location> locations)
47+
{
48+
return [.. locations];
49+
}
2650
}

src/GraphQL/Executor.ExecuteSubscription.cs

Lines changed: 84 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
using System.Runtime.CompilerServices;
1+
using System;
2+
using System.Runtime.CompilerServices;
3+
4+
using Microsoft.VisualBasic.FileIO;
25

36
using Tanka.GraphQL.Features;
47
using Tanka.GraphQL.Language.Nodes;
@@ -15,11 +18,11 @@ public partial class Executor
1518
/// </summary>
1619
/// <param name="context"></param>
1720
/// <returns></returns>
18-
public static Task ExecuteSubscription(QueryContext context)
21+
public static async Task ExecuteSubscription(QueryContext context)
1922
{
2023
context.RequestCancelled.ThrowIfCancellationRequested();
2124

22-
IAsyncEnumerable<object?> sourceStream = CreateSourceEventStream(
25+
IAsyncEnumerable<object?> sourceStream = await CreateSourceEventStream(
2326
context,
2427
context.RequestCancelled);
2528

@@ -29,7 +32,6 @@ public static Task ExecuteSubscription(QueryContext context)
2932
context.RequestCancelled);
3033

3134
context.Response = responseStream;
32-
return Task.CompletedTask;
3335
}
3436

3537

@@ -40,9 +42,9 @@ public static Task ExecuteSubscription(QueryContext context)
4042
/// <param name="cancellationToken"></param>
4143
/// <returns></returns>
4244
/// <exception cref="QueryException"></exception>
43-
public static async IAsyncEnumerable<object?> CreateSourceEventStream(
45+
public static async Task<IAsyncEnumerable<object?>> CreateSourceEventStream(
4446
QueryContext context,
45-
[EnumeratorCancellation] CancellationToken cancellationToken)
47+
CancellationToken cancellationToken)
4648
{
4749
ArgumentNullException.ThrowIfNull(context.Schema.Subscription);
4850

@@ -56,9 +58,9 @@ public static Task ExecuteSubscription(QueryContext context)
5658
);
5759

5860
List<FieldSelection> fields = groupedFieldSet.Values.First();
59-
Name fieldName = fields.First().Name;
6061
FieldSelection fieldSelection = fields.First();
61-
62+
Name fieldName = fieldSelection.Name;
63+
6264
IReadOnlyDictionary<string, object?> coercedArgumentValues = ArgumentCoercion.CoerceArgumentValues(
6365
context.Schema,
6466
subscriptionType,
@@ -68,7 +70,7 @@ public static Task ExecuteSubscription(QueryContext context)
6870
FieldDefinition? field = context.Schema.GetField(subscriptionType.Name, fieldName);
6971

7072
if (field is null)
71-
yield break;
73+
return AsyncEnumerableEx.Empty<object?>();
7274

7375
var path = new NodePath();
7476
Subscriber? subscriber = context.Schema.GetSubscriber(subscriptionType.Name, fieldName);
@@ -92,13 +94,60 @@ public static Task ExecuteSubscription(QueryContext context)
9294
QueryContext = context
9395
};
9496

95-
await subscriber(resolverContext, cancellationToken);
97+
try
98+
{
99+
await subscriber(resolverContext, cancellationToken);
96100

97-
if (resolverContext.ResolvedValue is null)
98-
yield break;
101+
if (resolverContext.ResolvedValue is null)
102+
return AsyncEnumerableEx.Empty<object?>();
103+
}
104+
catch (Exception exception)
105+
{
106+
if (exception is not FieldException)
107+
throw new FieldException(exception.Message, exception)
108+
{
109+
ObjectDefinition = subscriptionType,
110+
Field = field,
111+
Selection = fieldSelection,
112+
Path = path
113+
};
114+
115+
throw;
116+
}
117+
118+
return Core(resolverContext, cancellationToken);
119+
120+
static async IAsyncEnumerable<object?> Core(SubscriberContext resolverContext, [EnumeratorCancellation]CancellationToken cancellationToken)
121+
{
122+
await using var e = resolverContext.ResolvedValue!.GetAsyncEnumerator(cancellationToken);
99123

100-
await foreach (object? evnt in resolverContext.ResolvedValue.WithCancellation(cancellationToken))
101-
yield return evnt;
124+
while (true)
125+
{
126+
try
127+
{
128+
if (!await e.MoveNextAsync())
129+
{
130+
yield break;
131+
}
132+
133+
}
134+
catch (Exception exception)
135+
{
136+
if (exception is not FieldException)
137+
throw new FieldException(exception.Message, exception)
138+
{
139+
ObjectDefinition = resolverContext.ObjectDefinition,
140+
Field = resolverContext.Field,
141+
Selection = resolverContext.Selection,
142+
Path = resolverContext.Path
143+
};
144+
145+
throw;
146+
}
147+
148+
yield return e.Current;
149+
}
150+
}
102151
}
103152

104153
/// <summary>
@@ -109,25 +158,36 @@ public static Task ExecuteSubscription(QueryContext context)
109158
/// <param name="sourceStream"></param>
110159
/// <param name="cancellationToken"></param>
111160
/// <returns></returns>
112-
public static async IAsyncEnumerable<ExecutionResult> MapSourceToResponseEventStream(
161+
public static IAsyncEnumerable<ExecutionResult> MapSourceToResponseEventStream(
113162
QueryContext context,
114163
IAsyncEnumerable<object?> sourceStream,
115-
[EnumeratorCancellation] CancellationToken cancellationToken)
164+
CancellationToken cancellationToken)
116165
{
117166
ArgumentNullException.ThrowIfNull(context.Schema.Subscription);
118167

119168
ObjectDefinition? subscriptionType = context.Schema.Subscription;
120169
SelectionSet selectionSet = context.OperationDefinition.SelectionSet;
121170

122-
await foreach (object? sourceEvnt in sourceStream.WithCancellation(cancellationToken))
171+
return Core(context, sourceStream, subscriptionType, selectionSet, cancellationToken);
172+
173+
static async IAsyncEnumerable<ExecutionResult> Core(
174+
QueryContext context,
175+
IAsyncEnumerable<object?> sourceStream,
176+
ObjectDefinition subscriptionType,
177+
SelectionSet selectionSet,
178+
[EnumeratorCancellation] CancellationToken cancellationToken)
123179
{
124-
var path = new NodePath();
125-
yield return await ExecuteSourceEvent(
126-
context,
127-
selectionSet,
128-
subscriptionType,
129-
sourceEvnt,
130-
path);
180+
181+
await foreach (var sourceEvnt in sourceStream.WithCancellation(cancellationToken))
182+
{
183+
var path = new NodePath();
184+
yield return await ExecuteSourceEvent(
185+
context,
186+
selectionSet,
187+
subscriptionType,
188+
sourceEvnt,
189+
path);
190+
}
131191
}
132192
}
133193

src/GraphQL/Features/IErrorCollectorFeature.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@ public interface IErrorCollectorFeature
44
{
55
void Add(Exception error);
66
IEnumerable<ExecutionError> GetErrors();
7+
ExecutionError FormatError(Exception x);
78
}

0 commit comments

Comments
 (0)