Skip to content

Commit 49948d4

Browse files
committed
fix(api): add error handling for deserialization in data update
- Implement try-catch block around modelConfig.fromJson() to catch TypeError - Return 400 Bad Request response with error details when deserialization fails - Improve error message for client-side debugging
1 parent 2c28902 commit 49948d4

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

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

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,25 @@ Future<Response> onRequest(RequestContext context, String id) async {
6565
);
6666
}
6767

68-
// Deserialize using ModelConfig's fromJson
69-
final itemToUpdate = modelConfig.fromJson(requestBody);
68+
// Deserialize using ModelConfig's fromJson, catching TypeErrors
69+
dynamic itemToUpdate; // Use dynamic initially
70+
try {
71+
itemToUpdate = modelConfig.fromJson(requestBody);
72+
} on TypeError catch (e) {
73+
// Catch errors during deserialization (e.g., missing required fields)
74+
print('Deserialization TypeError in PUT /data/[id]: $e');
75+
return Response.json(
76+
statusCode: HttpStatus.badRequest, // 400
77+
body: {
78+
'error': {
79+
'code': 'INVALID_REQUEST_BODY',
80+
'message':
81+
'Invalid request body: Missing or invalid required field(s).',
82+
// 'details': e.toString(), // Optional: Include details in dev
83+
},
84+
},
85+
);
86+
}
7087

7188
// ID validation moved inside the switch block after type casting
7289

0 commit comments

Comments
 (0)