Skip to content

Commit 8064abe

Browse files
committed
refactor(api): improve error handling and type checking in PUT request
- Add try-catch block for more robust error handling when getting ID from request body - Implement type checking for UserContentPreferences before updating preferences - Log informative messages for potential errors - Improve error messages for better clarity and debugging
1 parent 86072df commit 8064abe

File tree

1 file changed

+24
-9
lines changed

1 file changed

+24
-9
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(

0 commit comments

Comments
 (0)