How Catch error : conection timed out, socketException in Flutter - flutter

Hi I tried to catch a socketException when the server I am consulting is not available, I tried with try{}catch{}, catchError and timeout, but it doesn't work
I need that if some time passes that the server does not respond, that it already stops waiting for it
The error is :
and I tried something like this

You are probably giving the code the wrong URL. Maybe this link will help You. Link. If You could just type in the URL and If You are using Python with flask or Django, or Node.js, that would help tremendously.
Update:
In the part where You say
final resp = await http.get(url).catchError({(onError) => print(onError)});
You should change it to this:
final resp = await http.get(url).catchError((onError) {
print(onError);
return null;
});
Because You are catching the Error in the response and only printing it. You should return null; and escape that function.
I hope this helped.

Related

Endpoint Not Responding

I'm trying to make CRUD app using mongodb atlas and express when i need to make an GET endpoint its not responding and keeps loading here the code
Get Endpoint:
app.get('/getTodo',(req, res) => {
const cursor = db.getDB().collection(coll).find({});
cursor.toArray(( todos) => {
res.send(todos);
});
}
});
I tried to catch the error using try catch there was no error then i tried to log something after it it logged. I also tried to user async and await samething nothing changed.
what should I do?? what I'm doing wrong??

FirebaseFunctionsException: code: -1007, too many HTTP redirects

I don't understand why I'm getting this error. It happens either on a virtual or real device. I try to uninstall the app and nothing change. Why a simple helloWord function throw this error. I have no console log displayed. In the log I have this message: "Request has invalid method. GET" then "Error: Invalid request, unable to process. at entryFromArgs..." Why redirect? Could it be related to the cloud region I change? How could I clean that. Thank you.
Below the cloud function.
exports.belleDiana = functions.region(CLOUD_REGION).https.onCall(async (data, context) : Promise<String> => {
console.log("belleDiana", data, context);
console.log("context.auth", context.auth?.uid, context);
return "belleDianaDone";
});
The call on flutter side.
try {
final result =
await FirebaseFunctions.instance.httpsCallable('belleDiana').call();
print("result: $result");
} on FirebaseFunctionsException catch (error) {
print(error);
print(error.code);
print(error.details);
print(error.message);
}
I switch to the original region 'us-central1'. When I change cloud region I have this message " Unhandled error cleaning up build images. This could result in a small monthly bill if not corrected. You can attempt to delete these images by redeploying or you can delete them manually at https://console.cloud.google.com/artifacts/docker/myproject/europe-west1/gcf-artifacts
"
After the deletion of that manually, every thing work as attended. I don't really understand why...

Mongoose save method seems to not be working

I am trying to create a REST API. I am pretty new to the back end and am just practicing on my own for the time being. For my code, I know it's bad practice to store the plain text password but again, this is completely for practice and will never go live. I will also add encryption at a later point for practice.
My issue is I am not sure why my API does not work. I see where it fails, it fails in the catch block when I try to save a user but I do not get any error to tell me what is wrong exactly, besides the once I force. I have another part on this website that follows almost the exact same logic and it works perfectly but for this one it does not. I have no idea how to solve my issue but after googling I still cannot figure it out. It looks perfectly fine too me, but as mentioned I am pretty new to the backend.
This is my controller function:
const signup = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(new HttpError('Invalid inputs passed, please check your data', 422));
}
const { name, email, password, places } = req.body;
let existingUser;
try {
existingUser = await User.findOne({email: email}) // finds one document matching our criteria we set
} catch(err) {
const error = new HttpError('Signing up failed, please try again later', 500);
return next(error);
}
if (existingUser) {
const error = new HttpError('User exists already, please login instead', 422);
return next(error);
}
const createdUser = new User({
name,
email,
image: 'https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260',
password,
places
});
try {
await createdUser.save();
} catch(err) {
const error = new HttpError(
'Signing up failed', 500
);
return next(error);
}
res.status(201).json({user: createdUser.toObject({ getters:true })});
};
I use Postman to send the request to my API endpoint with all of the correct information. Based on what I recieve back it is failing in the try catch block of await createdUser.save()
For anyone who finds this from google this was my solution:
First I suggest you add this into your save method to try and diagnose the problem
await createdUser.save(function(err){
if(err){
console.log(err);
return;
}
});
This help me greatly as it gave me more information on how to solve it.It turns out my problem was because I misspelled a field in my Schema. So extremely simple solution!

http.get returns 404 "Route not found"

I am trying to use a public API to search movie titles via my Flutter/Dart app.
A minimal code snippet is this
static Future<AnimeSearchResult> fetchSearchResults(String searchTerm) async {
final response = await http.get(
Uri.https("kitsu.io", "/api/edge/anime?filter[text]=cowboy%20bebop"));
// https://kitsu.io/api/edge/anime?filter[text]=cowboy%20bebop
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return animeSearchResultsFromMap(response.body);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
print(response.body);
throw Exception('Failed to load search results');
}
}
This will search and return an object back to a FutureBuilder Widget which then displays the results. (I have tested the UI and it is working on sample data)
Running the code, I get 404 error in my console
{"errors":[{"status":404,"title":"Route Not Found"}]}
Opening the link in my browser, it gives a JSON file as its supposed to do.
Trying to access the trending collection link using
final response = await http.get(Uri.https("kitsu.io", "/api/edge/trending/anime")); also works perfectly fine.
So I am suspecting there is some error in the way my URI is written for the search code. Precisely speaking, this line is at fault
final response = await http.get(Uri.https("kitsu.io", "/api/edge/anime?filter[text]=cowboy%20bebop"));
However I don't know what exactly is the problem.
Any help is appreciated!
Thank You!
I tried it this way, and it worked:
final response = await http.get(Uri.parse("https://kitsu.io/api/edge/anime?filter[text]=cowboy%20bebop"));
But await http.get(Uri.https resulted in the same error you are having.

FireStore read fails silently and I have no idea why

Help is much appreciated how to trace down this issue, because I am running out of ideas.
I am calling the function getOrderCollection, below, but it aborts after the first line var myCompanyDoc = await FirebaseFirestore.instance.collection('companies').doc(myCompany).get(); Without trowing anything to the console or jumping into some library when debugging. When I click next statement it jumps back to the calling function.
I am authenticated to the database, companyCollection = FirebaseFirestore.instance.collection('companies') provides an initialized object pointing to the collection and myCompany is a constant with the document id entered by copy/paste.
If some rules for the database but I can't see successful or denied queries with the monitor.
Any ideas how I can proceed tracing down the issue?
Future<void> getOrderCollection() async {
var myCompanyDoc = await FirebaseFirestore.instance.collection('companies').doc(myCompany).get();
print("companyDoc fetched");
final myDeliveryDocRef = myCompanyDoc.data()['delivery'].toString();
orderCollection = FirebaseFirestore.instance.collection('companies').doc(myCompany).collection('features').doc(myDeliveryDocRef).collection('orders');
orderBriefDoc = FirebaseFirestore.instance.collection('companies').doc(myCompany).collection('features').doc(myDeliveryDocRef);
}
UPDATE: This is collection > document what corresponds to final String myCompany = '4U4kZKXkr3rHA6B04S5K';
As we discussed in your comments, the issue was that you forgot to await the getOrderCollection() function. Even though, as you mentioned, your caller function _deliveryRepository.initRepository() was awaited, you still had to await getOrderCollection() inside your caller method to make sure that the code is waiting for the getOrderCollection() to be executed before it proceeds to the next line.
In general, you want to have some error handling and to type the known types/classes (avoid using var).
Error handling - for async/await place the code inside a try/catch.
Typing - Dart is type safe, which is really great to prevent runtime errors.
Depending on your setup, you might be able to hover over the Firestore.instance.collection(...).doc(...) to see the return type. .doc(...).get() returns a DocumentSnapshot and .collection(...).get() returns a CollectionSnapshot.
Using the above, it should be easier to debug:
Future<void> getOrderCollection() async {
try {
DocumentSnapshot myCompanyDoc = await FirebaseFirestore.instance.collection('companies').doc(myCompany).get();
print("companyDoc fetched");
final myDeliveryDocRef = myCompanyDoc.data()['delivery'].toString();
} catch(e) {
print('Error: ' + e.toString());
}
}
Don't forget to await your other 2 Firestore queries.