Skip to content

Commit 91217ba

Browse files
authored
Merge pull request #39 from flutter-news-app-full-source-code/enhance-a-data-route-error-handling-regression
Enhance a data route error handling regression
2 parents a3bf8c6 + 8064abe commit 91217ba

File tree

2 files changed

+59
-23
lines changed

2 files changed

+59
-23
lines changed

routes/api/v1/data/[id]/index.dart

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,18 +84,33 @@ Future<Response> _handlePut(RequestContext context, String id) async {
8484
);
8585
}
8686

87-
final bodyItemId = modelConfig.getId(itemToUpdate);
88-
if (bodyItemId != id) {
89-
throw BadRequestException(
90-
'Bad Request: ID in request body ("$bodyItemId") does not match ID in path ("$id").',
91-
);
87+
try {
88+
final bodyItemId = modelConfig.getId(itemToUpdate);
89+
if (bodyItemId != id) {
90+
throw BadRequestException(
91+
'Bad Request: ID in request body ("$bodyItemId") does not match ID in path ("$id").',
92+
);
93+
}
94+
} catch (e) {
95+
// Ignore if getId throws, as the ID might not be in the body,
96+
// which can be acceptable for some models.
97+
_logger.info('Could not get ID from PUT body: $e');
9298
}
9399

94100
if (modelName == 'user_content_preferences') {
95-
await userPreferenceLimitService.checkUpdatePreferences(
96-
authenticatedUser,
97-
itemToUpdate as UserContentPreferences,
98-
);
101+
if (itemToUpdate is UserContentPreferences) {
102+
await userPreferenceLimitService.checkUpdatePreferences(
103+
authenticatedUser,
104+
itemToUpdate,
105+
);
106+
} else {
107+
_logger.severe(
108+
'Type Error: Expected UserContentPreferences for limit check, but got ${itemToUpdate.runtimeType}.',
109+
);
110+
throw const OperationFailedException(
111+
'Internal Server Error: Model type mismatch for limit check.',
112+
);
113+
}
99114
}
100115

101116
final userIdForRepoCall = _getUserIdForRepoCall(

routes/api/v1/data/index.dart

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,34 @@ Future<Response> _handleGet(RequestContext context) async {
2828
final authenticatedUser = context.read<User>();
2929
final params = context.request.uri.queryParameters;
3030

31-
final filter = params.containsKey('filter')
32-
? jsonDecode(params['filter']!) as Map<String, dynamic>
33-
: null;
31+
Map<String, dynamic>? filter;
32+
if (params.containsKey('filter')) {
33+
try {
34+
filter = jsonDecode(params['filter']!) as Map<String, dynamic>;
35+
} on FormatException catch (e) {
36+
throw BadRequestException(
37+
'Invalid "filter" parameter: Not valid JSON. $e',
38+
);
39+
}
40+
}
3441

35-
final sort = params.containsKey('sort')
36-
? (params['sort']!.split(',').map((s) {
37-
final parts = s.split(':');
38-
final field = parts[0];
39-
final order = (parts.length > 1 && parts[1] == 'desc')
40-
? SortOrder.desc
41-
: SortOrder.asc;
42-
return SortOption(field, order);
43-
}).toList())
44-
: null;
42+
List<SortOption>? sort;
43+
if (params.containsKey('sort')) {
44+
try {
45+
sort = params['sort']!.split(',').map((s) {
46+
final parts = s.split(':');
47+
final field = parts[0];
48+
final order = (parts.length > 1 && parts[1] == 'desc')
49+
? SortOrder.desc
50+
: SortOrder.asc;
51+
return SortOption(field, order);
52+
}).toList();
53+
} catch (e) {
54+
throw const BadRequestException(
55+
'Invalid "sort" parameter format. Use "field:order,field2:order".',
56+
);
57+
}
58+
}
4559

4660
final pagination =
4761
(params.containsKey('limit') || params.containsKey('cursor'))
@@ -91,7 +105,14 @@ Future<Response> _handlePost(RequestContext context) async {
91105
requestBody['createdAt'] = now;
92106
requestBody['updatedAt'] = now;
93107

94-
final itemToCreate = modelConfig.fromJson(requestBody);
108+
dynamic itemToCreate;
109+
try {
110+
itemToCreate = modelConfig.fromJson(requestBody);
111+
} on TypeError catch (e) {
112+
throw BadRequestException(
113+
'Invalid request body: Missing or invalid required field(s). $e',
114+
);
115+
}
95116

96117
final userIdForRepoCall =
97118
(modelConfig.getOwnerId != null &&

0 commit comments

Comments
 (0)