Reputation: 622
i don't know what i am doing wrong or how to do it probably , in firebase it has been much easier with the FirebaseAuthException
but here in a normal api i dont know how to handle my failures , like when it is 404
i want to display a specific error but i have reached a dead end because the IDE always tells me that The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type. Try adding either a return or a throw statement at the end.
iam returning a failure ate the end so what's the problem ? and i want to handle every failure not only socketexception
.
thank you !
import 'dart:convert';
import 'dart:io';
import 'package:dartz/dartz.dart';
import 'package:mscmu/domain/i_api_request/failures/api.failures.dart';
import '../../../../domain/i_api_request/folders/contracts/i.folders.repository.dart';
import '../../../../domain/models/foldermodel.dart';
import 'package:http/http.dart' as http;
class FolderRepository implements IFolderRepository {
@override
Future<Either<ApiFailures, List<FolderModel>>> mainFolders(int courseId) async {
final response = await http.post(
Uri.parse("http://xxxxxxxxxxxxxxx.php"),
body: {"flag": "selectmainfolders", "course": "$courseId"}
);
try {
if (response.statusCode == 200) {
var l = json.decode(response.body) as List<dynamic>;
var folders = l.map((e) => FolderModel.fromJson(e)).toList();
return right(folders);
}
} on SocketException catch(error) {
return left(ApiFailures.badRequest());
}
}
}
Upvotes: 0
Views: 700
Reputation: 8383
You are missing an else statement:
class FolderRepository implements IFolderRepository {
@override
Future<Either<ApiFailures, List<FolderModel>>> mainFolders(int courseId) async {
final response = await http.post(
Uri.parse("http://xxxxxxxxxxxxxxx.php"),
body: {"flag": "selectmainfolders", "course": "$courseId"}
);
try {
if (response.statusCode == 200) {
[...]
return right(folders);
} else { // 404, 500, ...
[...]
return ???;
}
} on SocketException catch(error) {
return left(ApiFailures.badRequest());
}
}
}
If you use just a
if ([...]) {
[...]
return something;
}
or a
if ([...]) {
[...]
return something;
}
else if ([...]) {
[...]
return somethingElse;
}
Then, you are missing the else branch that will return null
and cause your error.
Upvotes: 1
Reputation: 2419
Your function must return something
that socketexception
wont work on every error ... you should add return something when the response.statusCode
is not 200
if (response.statusCode == 200) {
var l = json.decode(response.body) as List<dynamic>;
var folders = l.map((e) => FolderModel.fromJson(e)).toList();
return right(folders);
}else{
////////return something
}
you got to return Either<ApiFailures, List<FolderModel>>
as you have written in your function
Upvotes: 0