exception occurs when iterating through futures - grails

Can someone please explain to me what this piece of code does and how it can enter on the second catch clause, inside finally (without entering the first catch) and log this message "log.error("error while running closure", ee)" ?
try {
batches.each { batch -> futures << executorService.submit(['call':runClosure.curry(batch)] as Callable) }
} catch (Exception e) {
log.error("error: ", e)
} finally {
futures.each {
try {
it.get()
} catch (Exception ee) {
log.error("error while running closure", ee)
}
}
}
I have this piece of code that calls the method processBatch:
def runClosure = { batch ->
processBatch(batch)
}

Related

how to use the object inside catch

How to I convert the object inside catch?
class Sample {
final String? errorCode;
Sample({this.errorCode});
}
void main() {
var sample = Sample(errorCode: 'sample');
try {
throw sample;
} catch(err) {
print(err); // I would like to get the errorCode e.g. err.errorcode
}
}
Either make sure to only catch a Sample, then err will have that type:
} on Sample catch (error) {
print(error.errorCode);
}
or check/cast inside the catch block:
} catch (error) {
if (error is Sample) print(error.errorCode);
print((error as Sample).errorCode);
}
The first approach is safer if you only expect to catch a Sample.
The is-check can be used if you want to catch other things too, but treat Sample specially.
The as should not be used outside of quick-and-dirty code, because it can throw if you catch something other than a Sample, and you don't want your error handling to throw!

Connection and unknown errors in FlutterFire Messaging (iOS Only)

I implemented FlutterFire Messaging with the subscribeToTopic method, as the snippet below:
final _topics = ['topicName'];
Future<void> subscribeTopics() async {
for (final topic in _topics) {
await FirebaseMessaging.instance.subscribeToTopic(topic);
}
}
Future<void> unsubscribeTopics() async {
for (final topic in _topics) {
await FirebaseMessaging.instance.unsubscribeFromTopic(topic);
}
}
And everything is fine in debug mode, but in my Crashlytics I'm receiving some reports about it (iOS only):
[firebase_messaging/unknown] The request timed out
[firebase_messaging/unknown] An unknown error has occurred
[firebase_messaging/unknown] A data connection is not currently allowed
[firebase_messaging/unknown] The Internet connection appears to be offline
All the errors appears to be about internet connection, so my question is: "Should I validate the user connection before use FCM or the lib is ready to deal with it but only in Android?"
Crashlytics Stacktrace
Non-fatal Exception: FlutterError
0 ??? 0x0 MethodChannelFirebaseMessaging.subscribeToTopic + 368 (method_channel_messaging.dart:368)
1 ??? 0x0 Messaging.subscribeTopics + 40 (messaging.dart:40)
2 ??? 0x0 Messaging.observeMessaging + 22 (messaging.dart:22)
It's a general error so you shouldn't worry about it. When the internet connection restores the method will hopefully restart itself. You should also consider the case that It might generate an error while the app is in the background.
You can use try catch block to avoid these messages in your crashlytics dashboard.
final _topics = ['topicName'];
Future<void> subscribeTopics() async {
try {
for (final topic in _topics) {
await FirebaseMessaging.instance.subscribeToTopic(topic);
}
} on FirebaseException {
// do nothing
}
}
Future<void> unsubscribeTopics() async {
try {
for (final topic in _topics) {
await FirebaseMessaging.instance.unsubscribeFromTopic(topic);
}
} on FirebaseException {
// do nothing
}
}
Note It will also ignore all other error messages too. In that case
You can handle it otherwise
final _topics = ['topicName'];
Future<void> subscribeTopics() async {
try {
for (final topic in _topics) {
await FirebaseMessaging.instance.subscribeToTopic(topic);
}
} on FirebaseException catch (e) {
if (e.code == 'unknown') {
// do nothing
} else {
// do something
}
}
}
Future<void> unsubscribeTopics() async {
try {
for (final topic in _topics) {
await FirebaseMessaging.instance.unsubscribeFromTopic(topic);
}
} on FirebaseException catch (e) {
if (e.code == 'unknown') {
// do nothing
} else {
// do something
}
}
}

Mqtt: Persist message on server side

We decided to use mqtt protocol for chat module in our mobile application. I want to save messages of topic in server side also. But i saw,mqtt client is global here,so one way is i have to subscribe single instance of mqtt client to all topics and save messages in database. but is it right approach to do it. i am just worring about it.
private void buildClient(){
log.debug("Connecting... "+CLIENT_ID);
try {
mqttClient = new MqttClient(envConfiguration.getBrokerUrl(), CLIENT_ID);
} catch (MqttException e) {
log.debug("build client stopped due to "+e.getCause());
}
chatCallback = new ChatCallback();
mqttClient.setCallback(chatCallback);
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(false);
}
#Override
public void connect() {
if(mqttClient == null || !mqttClient.getClientId().equals(CLIENT_ID)){
buildClient();
}
boolean tryConnecting = true;
while(tryConnecting){
try {
mqttClient.connect(mqttConnectOptions);
} catch (Exception e) {
log.debug("connection attempt failed "+ e.getCause() + " trying...");
}
if(mqttClient.isConnected()){
tryConnecting = false;
}else{
pause();
}
}
}
#Override
public void publish() {
boolean publishCallCompletedErrorFree = false;
while (!publishCallCompletedErrorFree) {
try {
mqttClient.publish(TOPIC, "hello".getBytes(), 1, true);
publishCallCompletedErrorFree = true;
} catch (Exception e) {
log.debug("error occured while publishing "+e.getCause());
}finally{
pause();
}
}
}
#Override
public void subscribe() {
if(mqttClient != null && mqttClient.isConnected()){
try {
mqttClient.subscribe(TOPIC, 2);
} catch (MqttException e) {
log.debug("subscribing error.."+e.getCause());
}
}
}
#Override
public void disconnect() {
System.out.println(this.mqttClient.isConnected());
try {
mqttClient.disconnect();
log.debug("disconnected..");
} catch (MqttException e) {
log.debug("erro occured while disconneting.."+e.getCause());
}
}
There are two possibilities how to solve this issue:
Write a MQTT client that subscribes to all topics using a wildcard (# in MQTT)
Write a broker plugin that does the job for you, depending on the broker implementation you're using
There is a good description of how to implement both options at the HiveMQ website, also describing limitations of the first option.

Windows Service just stops. No messages, no alerts, errors, warning - nothing

I have a Windows service that just silently stops on its own. Here is the relevant code:
OnStart() method:
protected override void OnStart(string[] args)
{
try
{
InitializeLogging();
// we don't DO command line arguments
if (args.Length > 0)
{
eventLog.WriteEntry("All command line arguments are ignored. You must edit the app.config file manually to make changes to what watchers are run.");
throw new ArgumentException("Command line arguments are ignored.");
}
ReadAppConfig();
RecalculateStartTimes();
InitializeWatchers();
}
catch (Exception e)
{
eventLog.WriteFormattedEntry("Error on Start: {0}", e.Message);
}
finally
{
eventLog.WriteEntry("Service start completed");
}
}
OnStop() method:
protected override void OnStop()
{
eventLog.WriteEntry("Service stopped.");
}
InitializeWatchers() method:
private void InitializeWatchers()
{
try
{
var watchers = _watcherSection.Watchers.ToList<WatcherElement>();
eventLog.WriteEntry(string.Format("Initializing {0} watchers.", watchers.Count()));
var obsWatchers = watchers.ToObservable();
obsWatchers.SelectMany(
watcher =>
Observable.Timer(watcher.StartTime, TimeSpan.FromHours(watcher.Interval))
.SelectMany(
Observable.FromAsync(
async () => new
{
watcher,
response = await CheckFolder(watcher.Path)
})))
.Subscribe(
onNext: x =>
{
eventLog.WriteFormattedEntry("\nWatcher: {0}, Time:{1}", x.watcher.Name, DateTimeOffset.Now);
if (x.response.Success)
eventLog.WriteFormattedEntry("| Success!\n| Value: '{0}'\n| Message: {0}", x.response.Value, x.response.Message);
else
eventLog.WriteFormattedEntry("| FAILURE!\n| Value: '{0}'\n| Message: {0}\n| Errors: '{0}'", x.response.Value, x.response.Message, x.response.Exceptions.First());
},
onError: e =>
{
var err = e;
var sb = new StringBuilder();
sb.AppendLine("The observer threw an error:")
.AppendFormatLine("| Message: {0}", e.Message);
while (e.InnerException != null)
{
sb.AppendFormatLine("| Inner: {0}", e.InnerException.Message);
e = e.InnerException;
}
sb.AppendLine();
eventLog.WriteEntry(sb.ToString());
throw err;
});
eventLog.WriteEntry("about to wait.");
obsWatchers.Wait();
eventLog.WriteEntry("passed the wait");
}
catch (Exception e)
{
eventLog.WriteFormattedEntry("Exception thrown in InitializeWatchers(WatchersSection): {0}", e.Message);
throw;
}
}
When I run this code, the service starts normally. The event log records three events:
Service & Logging started.
Initializing 1 watchers.
Service start completed.
... and it stops. I have to manually refresh the Services window, but it quits running. I don't get any errors, or any of the other eventLog entries.
The frustrating thing is that this code works perfectly as a Console app. I've changed all the eventLog.WriteEntry() to Console.WriteLine(), but other than that, the code is identical and performs as expected.
Any wisdom would be appreciated.
I suspect that the Service Control Manager is terminating your service because it did not return from OnStart within the timeout window (30 seconds, IIRC).
I have a blog post on managed service basics, which is based on a blog entry by the BCL team. Note that the MSDN docs are insufficient; you must know the information in the BCL team blog post to correctly write a managed service.
Instead of using obsWatchers.Wait() which blocks and causes the problems Stephen has said, just asynchronously subscribe.
Add this property to your class:
private SingleAssignmentDisposable _subscription = new SingleAssignmentDisposable();
Add this to your OnStop method:
_subscription.Dispose();
In your InitializeWatchers(), eliminate the nested call to Subscribe and replace obsWatchers.Wait() with a call to subscribe, like so:
private void InitializeWatchers()
{
try
{
var watchers = _watcherSection.Watchers.ToList<WatcherElement>();
eventLog.WriteEntry(string.Format("Initializing {0} watchers.", watchers.Count()));
var obsWatchers = watchers.ToObservable();
_subscription.Disposable = obsWatchers
.SelectMany(watcher => Observable
.Timer(watcher.StartTime, TimeSpan.FromHours(watcher.Interval))
.SelectMany(_ => Observable.FromAsync(async () => new
{
watcher,
response = await CheckFolder(watcher.Path)
})))
.Subscribe(
onNext: x =>
{
eventLog.WriteFormattedEntry("\nWatcher: {0}, Time:{1}", x.watcher.Name, DateTimeOffset.Now);
if (x.response.Success)
eventLog.WriteFormattedEntry("| Success!\n| Value: '{0}'\n| Message: {0}", x.response.Value, x.response.Message);
else
eventLog.WriteFormattedEntry("| FAILURE!\n| Value: '{0}'\n| Message: {0}\n| Errors: '{0}'", x.response.Value, x.response.Message, x.response.Exceptions.First());
},
onError: e =>
{
var err = e;
var sb = new StringBuilder();
sb.AppendLine("The observer threw an error:")
.AppendFormatLine("| Message: {0}", e.Message);
while (e.InnerException != null)
{
sb.AppendFormatLine("| Inner: {0}", e.InnerException.Message);
e = e.InnerException;
}
sb.AppendLine();
eventLog.WriteEntry(sb.ToString());
throw err;
});
eventLog.WriteEntry("passed the wait");
}
catch (Exception e)
{
eventLog.WriteFormattedEntry("Exception thrown in InitializeWatchers(WatchersSection): {0}", e.Message);
throw;
}
}

Deferring persistence as device is being used in BlackBerry when listening file change

I tried to listen file change event in BlackBerry base on FileExplorer example, but whenever I added or deleted file, it always showed "Deferring persistence as device is being used" and I can't catch anything .Here is my code:
public class FileChangeListenner implements FileSystemJournalListener{
private long _lastUSN; // = 0;
public void fileJournalChanged() {
long nextUSN = FileSystemJournal.getNextUSN();
String msg = null;
for (long lookUSN = nextUSN - 1; lookUSN >= _lastUSN && msg == null; --lookUSN)
{
FileSystemJournalEntry entry = FileSystemJournal.getEntry(lookUSN);
// We didn't find an entry
if (entry == null)
{
break;
}
// Check if this entry was added or deleted
String path = entry.getPath();
if (path != null)
{
switch (entry.getEvent())
{
case FileSystemJournalEntry.FILE_ADDED:
msg = "File was added.";
break;
case FileSystemJournalEntry.FILE_DELETED:
msg = "File was deleted.";
break;
}
}
}
_lastUSN = nextUSN;
if ( msg != null )
{
System.out.println(msg);
}
}
}
Here is the caller:
Thread t = new Thread(new Runnable() {
public void run() {
new FileChangeListenner();
try {
Thread.sleep(5000);
createFile();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
Create file method worked fine:
private void createFile() {
try {
FileConnection fc = (FileConnection) Connector
.open("file:///SDCard/newfile.txt");
// If no exception is thrown, then the URI is valid, but the file
// may or may not exist.
if (!fc.exists()) {
fc.create(); // create the file if it doesn't exist
}
OutputStream outStream = fc.openOutputStream();
outStream.write("test content".getBytes());
outStream.close();
fc.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
and output:
0:00:44.475: Deferring persistence as device is being used.
0:00:46.475: AG,+CPT
0:00:46.477: AG,-CPT
0:00:54.476: VM:+GC(f)w=11
0:00:54.551: VM:-GCt=9,b=1,r=0,g=f,w=11,m=0
0:00:54.553: VM:QUOT t=1
0:00:54.554: VM:+CR
0:00:54.596: VM:-CR t=5
0:00:55.476: AM: Exit net_rim_bb_datatags(291)
0:00:55.478: Process net_rim_bb_datatags(291) cleanup started
0:00:55.479: VM:EVTOv=7680,w=20
0:00:55.480: Process net_rim_bb_datatags(291) cleanup done
0:00:55.481: 06/25 03:40:41.165 BBM FutureTask Execute: net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
0:00:55.487: 06/25 03:40:41.171 BBM FutureTask Finish : net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
I also tried to remove the thread or create or delete file in simulator 's sdcard directly but it doesn't help. Please tell me where is my problem. Thanks
You instantiate the FileChangeListenner, but you never register it, and also don't keep it as a variable anywhere. You probably need to add this call
FileChangeListenner listener = new FileChangeListenner();
UiApplication.getUiApplication().addFileSystemJournalListener(listener);
You also might need to keep a reference (listener) around for as long as you want to receive events. But maybe not (the addFileSystemJournalListener() call might do that). But, you at least need that call to addFileSystemJournalListener(), or you'll never get fileJournalChanged() called back.

Resources