Refactor API error handling and add try-catch blocks

Added try-catch blocks for error handling in API's files to rethrow the errors to the cubit so cubits can update the UI based on them.

Refactored error handling in HTTPInterceptor and HTTPService classes.
This commit is contained in:
Mohammad Salameh
2024-04-15 15:47:13 +03:00
parent dd90a2133f
commit df13c66b1a
9 changed files with 247 additions and 191 deletions

View File

@ -12,47 +12,39 @@ class SpacesAPI {
static Future<List<SpaceModel>> getSpaces() async {
var uuid =
await const FlutterSecureStorage().read(key: UserModel.userUuidKey);
final response = await _httpService.get(
path: ApiEndpoints.spaces,
queryParameters: {
"userUuid": uuid,
},
showServerMessage: false,
expectedResponseModel: (json) => SpaceModel.fromJsonList(json),
);
return response;
try {
final response = await _httpService.get(
path: ApiEndpoints.spaces,
queryParameters: {
"userUuid": uuid,
},
showServerMessage: false,
expectedResponseModel: (json) => SpaceModel.fromJsonList(json),
);
return response;
} catch (e) {
rethrow;
}
}
//get rooms by space id
static Future<List<RoomModel>> getRoomsBySpaceId(int spaceId) async {
final response = await _httpService.get(
path: ApiEndpoints.rooms,
queryParameters: {"homeId": spaceId},
showServerMessage: false,
expectedResponseModel: (json) {
List<RoomModel> rooms = [];
for (var room in json) {
rooms.add(RoomModel.fromJson(room));
}
return rooms;
},
);
return response;
}
static Future<List<DeviceModel>> getDevicesByRoomId(int roomId) async {
final response = await _httpService.get(
path: ApiEndpoints.devicesByRoom,
queryParameters: {"roomId": roomId, "pageSize": 10},
showServerMessage: false,
expectedResponseModel: (json) {
List<DeviceModel> devices = [];
for (var device in json['devices']) {
devices.add(DeviceModel.fromJson(device));
}
return devices;
},
);
return response;
try {
final response = await _httpService.get(
path: ApiEndpoints.rooms,
queryParameters: {"homeId": spaceId},
showServerMessage: false,
expectedResponseModel: (json) {
List<RoomModel> rooms = [];
for (var room in json) {
rooms.add(RoomModel.fromJson(room));
}
return rooms;
},
);
return response;
} catch (e) {
rethrow;
}
}
}