Skip to content

Commit 995e6bd

Browse files
authored
fix(api): web socket error handling (#5359)
1 parent db95ad0 commit 995e6bd

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

packages/api/amplify_api_dart/lib/src/graphql/web_socket/types/web_socket_types.dart

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,15 @@ class WebSocketError extends WebSocketMessagePayload implements Exception {
144144
final List<Map<String, dynamic>> errors;
145145

146146
static WebSocketError fromJson(Map<String, dynamic> json) {
147-
final errors = json['errors'] as List?;
148-
return WebSocketError(errors?.cast() ?? []);
147+
final errors = json['errors'];
148+
List<Map<String, dynamic>>? errorsList = [];
149+
if (errors is List?) {
150+
errorsList = errors?.cast();
151+
} else if (errors is Map<String, dynamic>) {
152+
errorsList = [errors];
153+
}
154+
155+
return WebSocketError(errorsList ?? []);
149156
}
150157

151158
@override

packages/api/amplify_api_dart/test/web_socket/web_socket_types_test.dart

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,34 @@ void main() {
113113
errors,
114114
);
115115

116+
/// GraphQLResponseDecoder should handle a payload with errors.
117+
final response = GraphQLResponseDecoder.instance.decode<String>(
118+
request: GraphQLRequest<String>(
119+
document: '',
120+
),
121+
response: message.payload!.toJson(),
122+
);
123+
expect(
124+
response.errors.first.message,
125+
errorMessage,
126+
);
127+
});
128+
test('WebsocketMessage should decode errors as a Map', () {
129+
const errorMessage = 'Max number of 100 subscriptions reached';
130+
const errorType = 'MaxSubscriptionsReachedError';
131+
const errorMap = {'errorType': errorType, 'message': errorMessage};
132+
final entry = {
133+
'id': 'xyz-456',
134+
'type': 'error',
135+
'payload': {'data': null, 'errors': errorMap},
136+
};
137+
final message = WebSocketMessage.fromJson(entry);
138+
expect(message.messageType, MessageType.error);
139+
expect(
140+
message.payload!.toJson()['errors'],
141+
[errorMap],
142+
);
143+
116144
/// GraphQLResponseDecoder should handle a payload with errors.
117145
final response = GraphQLResponseDecoder.instance.decode<String>(
118146
request: GraphQLRequest<String>(

0 commit comments

Comments
 (0)