Flutter & Dart Error Handling Middleware Concept - flutter

I check my errors between try blocks. How can I get rid of code repetition by creating an intermediate layer instead of rewriting it within each method?
As seen in the codes, I use try blocks in all operations.
Future<List<Post>> getAll(){
try {
//http get code
}on SocketException {
throw Failure('Message');
}on HttpException {
throw Failure("Http Exception Message");
}on FormatException {
throw Failure("Format Message");
}
}
Future<Post> getPost(){
try {
//http get code
}on SocketException {
throw Failure('Message');
}on HttpException {
throw Failure("Http Exception Message");
}on FormatException {
throw Failure("Format Message");
}
}

Related

Flutter: How do I avoid repetition of try-catch-exception?

This is the code I want to avoid repeating. If possible also try block.
try {
//
} on TimeoutException catch (e) {
log('Timeout Error: $e');
rethrow;
} on SocketException catch (e) {
log('Socket Error: $e');
rethrow;
} on Error catch (e) {
log('General Error: $e');
rethrow;
} catch (e) {
log('All other Errors: $e');
rethrow;
}
You could define a function like:
void tryCatch(Function f) {
try {
f();
} on TimeoutException catch (e) {
log('Timeout Error: $e');
rethrow;
} on SocketException catch (e) {
log('Socket Error: $e');
rethrow;
} on Error catch (e) {
log('General Error: $e');
rethrow;
} catch (e) {
log('All other Errors: $e');
rethrow;
}
}
and then anywhere you want to use it do
tryCatch((){
//your code here
});
One trivial answer could be to refactor that try-catch cascade in a dedicated function or class, in which you return the value if everything's all right, or handle the corresponding error.
I guess yours is just an example code, but if you're just interested in logging an error and then rethrow, you don't need to distinguish between those exceptions and errors.
You can easily retrieve your error's type like so:
try {
// some risky code
} catch(error, stackTrace) {
print(error.runtimeType);
print(error); // calls its internal toString() method
rethrow;
}
Even the above example could be refactored in a dedicated function or class, by the way.
If you're looking into something even more specific let me know, because I'm kinda curious about this, too.

catchError and "try - catch" is not working (async)

My code is trying to communicate using Socket, but I can't seem to catch the exception.
I've tried these things, but they don't work and I get an exception on the IDE.
Socket socket;
try {
socket = await Socket.connect(ip, port);
// Instead of jumping to errorProcess(), the IDE will show an exception here...
} catch(e) {
errorProcess(e);
}
Socket socket = await Socket.connect(ip, port).catchError((e) {
errorProcess(e);
// catchError says we need to return FutureOr<Socket>...
});
How can I catch exceptions?
Try adding SocketException for your try catch statement.
Example Code:
try {} on SocketException catch (e) {
print(e);
} catch (e) {
print(e);
}

What's the best practice to throw an Exception in Flutter

I have an exception that gets thrown multiple times before getting handled in my code, (the same error object gets thrown 4 times in the tree).
During each throw , flutter appends the word Exception: to my error object, so the final shape of the message is:
Exception: Exception: Exception: Exception: SocketException: OS Error: Connection refused, errno = 111, address = 10.12.7.15, port = 39682
And this is an example of how I handle exceptions:
getSomeData () async {
try {
await myFunction3();
} catch (e) {
throw Exception(e);
}
}
/*****************************************/
Future<void> myFunction3 () async {
try {
await myFunction2();
} catch (e) {
throw Exception(e);
}
}
/*****************************************/
Future<void> myFunction2 () async {
try {
await myFunction1();
} catch (e) {
throw Exception(e);
}
}
/*****************************************/
Future<void> myFunction1() async {
try {
await dio.get(/*some parameters*/);
}
on DioError catch (e) {
throw Exception(e.error);
}
catch (e) {
throw Exception(e);
}
}
I want to throw the Exception() in a right way so the repetition of word Exception: doesn't appear anymore in my error string.
Instead of throwing a new exception, you could rethrow the catched one:
Future<void> myFunction1() async {
try {
await dio.get(/*some parameters*/);
}
on DioError catch (e) {
// do something
rethrow;
}
catch (e) {
// do something
rethrow;
}
}
See more: https://dart.dev/guides/language/effective-dart/usage#do-use-rethrow-to-rethrow-a-caught-exception

FormatException: Scheme not starting with alphabetic character - Flutter Http Request

I make a http request in my flutter app with a simple url api:
Future<http.Response> getUsers() async {
try {
return await http
.get('​https://reqres.in/api/users')
.timeout(const Duration(seconds: 10))
.catchError((e) {
print("=> catchError getUsers $e");
return null;
});
} on SocketException catch (e) {
print("=> catch SocketException getUsers $e");
return null;
} catch (e) {
print("=> catch getUsers $e");
return null;
}
}
And the error message is:
err FormatException: Scheme not starting with alphabetic character (at character 1)
​https://reqres.in/api/users
^
I have switched to different channels of the flutter version and I don't know the solution, thanks!
Try using
http.get(Uri.parse('​https://reqres.in/api/users'))

How to catch http.get (SocketException)

I'm new to Flutter & Dart, trying to complete my first app.
I can't catch (with try-catch block) http.get SocketException (which happens when you call API and WiFi turned off)
I tried everything on the internet without luck, I even tried (Dio) package to catch this exception, but no success.
How to reproduce: use bottom code...turn off phone's WiFi...call API...now the app crashes with (SocketException) in your IDE.
Image: https://imgur.com/bA0rKEN
here is my simple code (updated)
RaisedButton(
child: Text("Call API"),
onPressed: () async {
try {
http.Response response = await getLoginResponse();
//do something with response
print(response.body);
} catch (e) {
print("Button onPressed Error: " + e.toString());
}
},
)
//---------------------------------------------------------------
Future<http.Response> getLoginResponse() {
return http.get(loginUrl).timeout(Duration(seconds: 10))
.then((response) {
return response;
}, onError: (e) {
print("onError: " + e.toString());
}).catchError((err) {
print("catchError: " + err.toString());
return null;
});
}
You can catch several types of errors and handle each one separately
Example:
import 'dart:io' as Io;
http.Client client = http.Client();
try {
response = await client.get(url).timeout(new Duration(seconds: 10));
} on Io.SocketException catch (_) {
throw Exception('Not connected. Failed to load data');
} on TimeoutException catch (_) {
throw Exception('Not connected. TimeOut Exception');
} catch (e) {
// Default error handling;
}
if you want to get catch in RaisedButton's try-catch block, instead of return null in getLoginInfo() methods, you must return an Exception like this:
Future<List<LoginObject>> getLoginInfo() async {
try {
List<LoginObject> loginObjectList = List<LoginObject>();
http.Response loginResponse =
await http.get(loginUrl).timeout(Duration(seconds: 10));
if (loginResponse.statusCode == 200) {
loginObjectList = loginObjectFromJson(loginResponse.body);
return loginObjectList;
} else {
throw Exception('Authentication Error');
}
} catch (e) {
print("Error: " + e.toString());
return throw Exception('Connection Error');;
}
}
Note: If you want to handle each one of error response, you can create an custom ErrorModelClass and handle error state with it and finally return your ErrorModelClass.
catch (error) {
print(error);
throw error is HttpResponseError ? error : HttpResponseError(0,"error connection");
HttpResponseError is my custom model class.