Flutter: Catch firebase messaging connection - flutter

I implemented fiebase messaging in my flutter application. I am trying to catch it's connection error for example something like this:
6.26.0 - [Firebase/Messaging][I-FCM002025] Failed to connect to direct channel, error: Error Domain=com.google.fcm Code=4 "No internet available, cannot connect to FIRMessaging" UserInfo={NSLocalizedFailureReason=No internet available, cannot connect to FIRMessaging}
but there is no place to catch it. How can i catch firebase messaging connection?
final FirebaseMessaging _fcm = FirebaseMessaging();
_fcm.getToken().then((value) {
_token = value;
print("Message token is: $_token");
}, onError: (err) {
print("getToken onError is: $err");
}).catchError((onError) {
print("getToken catchError is: $onError");
});

Related

Firebase Cloud Messaging (Flutter): Error message when subscribing to topic

I have included Firebase Messaging in my app and I am getting the following error when I try to subscribe to topics.
FLTFirebaseMessaging: An error occurred while calling method Messaging#subscribeToTopic, errorOrNil => {
NSLocalizedFailureReason = "Invalid registration response :'Error=INVALID_PARAMETERS'. It is missing 'token' field.";
}
flutter: subscription error: [firebase_messaging/unknown] An unknown error has occurred.
As you can see it simply says "An unknown error has occurred", which is not very helpful to me.
Here is my code which is meant to obtain permissions for push notifications, then gets the token and subscribes to a list of topics...
Future<void> requestMessagingPermission() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;
NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
print('User granted permission: ${settings.authorizationStatus}');
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted notifiactions permission');
messaging.getToken().then((token) async {
print('Messaging token: $token');
//configure notification topics
//gets a list of strings (topic names) from provider and loops through them to subscribe to them all
GlobalProvider provider = context.read<GlobalProvider>();
if (provider.notificationTopicsSet == false) {
//subscribe to topics
for (var topic in provider.notificationTopics) {
print('topic subscribing... $topic');
try {
await messaging.subscribeToTopic(topic).then((value) => print('topic subscribed: $topic'));
} catch (e) {
print('subscription error: $e');
}
}
}
});
}
}
I am getting the same error in the console for every topic that is being looped through and subscribed to. The weird thing is that push notifications were working before, but now they don't seem to be.
I have tried updating Flutter to the latest version (3.3.7), I have tried updating both the Firebase Core package (2.1.1) and the Firebase messaging package to their latest versions (14.0.4) and I am still getting the error.
From pubspec.yaml:
firebase_core: ^2.1.1
firebase_messaging: ^14.0.4
What is this token that is missing? The subscribeToTopic() function only seems to take the topic name string. Am I missing something?
Thank you, any help will be greatly appreciated.
This ended up being only an issue with the iOS simulator. The error did not occur with the Android emulator and push notifications work fine on physical devices.

Flutter Websocket giving feedback as NULL problem

Hello,
I am working with a login that works with websocket, when I send the correct parameters, the login connection is provided.It doesn't return me a statuscode 201 style message even if the connection is established.When I enter it wrong on purpose, it returns me this as an errorWebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'the url i entered#' was not upgraded to websocket the code is like this;
IOWebSocketChannel channel = new IOWebSocketChannel.connect("THE URL I ENTERED",headers: {"USER_ID":widget.user,"PASSWORD":widget.password},);
channel.stream.listen(
(dynamic message) {
debugPrint('message $message');
channel.sink.close(status.goingAway);
print(status.goingAway);
},
onDone: () {
debugPrint('ws channel closed');
},
onError: (error) {
print('socket closed: reason=[${channel.closeReason}], code:[${channel.closeCode}]');
debugPrint('ws error $error');
},
);
message i get in terminal
I/flutter ( 5598): socket closed: reason=[null], code:[null]
I/flutter ( 5598): ws error WebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'THE URL I ENTERED' was not upgraded to websocket
I/flutter ( 5598): ws channel closed
My question is, I want it to return server respond code when I entered correctly or when I entered wrong. I did the same thing in different languages ​​such as python, and it gives me feedback.
but here it comes only as null, I searched everywhere for the solution of this error for about 4 days, but I couldn't find it.waiting for you to help me
Best Regards

Flutter not able connect to websocket

When I try to connect to my nodejs server it is showing me this error-
connect_error: [{"cause":{"detailMessage":"Control frames must be final.","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"websocket error","stackTrace":[],"suppressedExceptions":[]}]
I used flutter_socket_io for socket connection
My flutter code
socketIO = SocketIOManager().createSocketIO(
websocketUrl, '/', socketStatusCallback: (status) {
print("web socket -------------status");
print(status);
if (status.toString() == "connect") {
print("connected to server with websocket------------------------");
// socketIO.sendMessage("socket request", jsonEncode({"id": id}));
}
});
socketIO.init();
socketIO.connect().then((value){
print('socket connect');
});

Flutter while Making any Http Request on real device to server reports wrong port number in logs

static String baseurl ="http://10.183.121.43:5000/";
try { Response response = await Dio().get(constant.baseurl+"hello/"); print(response); } catch (e) { print(e); }
----------
try {
await RawSocket.connect("10.183.121.43", 5000);
} catch (e) {
print(e);
}
----------
SocketException: OS Error: Connection timed out, errno = 110, address = 10.183.121.43, port = 55705
How I can fix it?
I am working on a real device .. and from the real device this IP and port working properly because I tested with the android app postman I am getting response of my api ..
Same if i used Ngrok and pass ngrok address instead of IP then it also working .. But by Passing IP http://10.183.121.43:5000/" this is not working

What is the proper way of detecting network errors in stream downloads using Axios in Nest.js?

I'm working with the HttpService module from Nest.js to make the HTTP calls. I'm able to download an image from https://unsplash.com; when there is no network interruptions the code is working as expected.
This is the code I have for making the download call and start writing into the desired file
const urlDownload = 'https://unsplash.com/photos/xiie4XeSzTU/download?force=true';
let response = await this.httpService.get(urlDownload, {
responseType: 'stream'
}).toPromise();
response.data.pipe(writer);
And this is the code where I'm trying to handle the possible events of the writer and returning a response
let downloadFile = path.resolve(__dirname,'../../files/landscape.jpg');
let writer = fs.createWriteStream(downloadFile);
return new Promise((resolve, reject) => {
writer.on('finish', ()=>{
resolve('Image downloaded');
});
writer.on('error', ()=>{
reject('Image downloaded failed');
});
});
I'm deliberately turning off the wifi during the download to try the server response with Image downloaded failed (what I have in the writer error handler), but instead I'm getting an 500 statusCode, internal server error. When I go to the Nest console to whatch the error it appears
[Nest] 11220 - 2020-05-22 18:16:45 [ExceptionsHandler] getaddrinfo ENOTFOUND unsplash.com +439536ms
Error: getaddrinfo ENOTFOUND unsplash.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:64:26)
How can I solve this and catch correcty the network error from Nest to return a friendly message?
I could solve it. I let it here with the hope of helping somebody in the future.
It is not firing the error handler function because that handler is attached to the writter, and there is not writting error, it just stops writing because the cut of the connection but that is not an error.
I re-writed the response variable to stop being a promise and better I started treating it like an observer.
let response = this.httpService.get(urlDownload, {
responseType: 'stream',
});
And then it is the response in previus Promise format
return new Promise((resolve, reject) => {
writer.on('error', () => {
resolve('error due to, possibly, an unexisting file path');
})
response.subscribe({
next(response) { response.data.pipe(writer) },
error(err) {
console.error('More details: ' + err);
resolve('Error in the download :/')
},
complete() { resolve('Completed'); }
})
});
I'm not using the reject function of the promise but it is perfectly doable