Can't catch Exception. Getting unhandled exception - dart

I have follow code. I need to handle Exception in it, but I can't do it. And can't understand the reason.
try {
print("aaa");
List<List<dynamic>> result =
await connection.query(sql).timeout(Duration(seconds: 120));
print('bbb');
if (result.isEmpty) {
sql = """ ... """;
await connection.query(sql);
} else {
int dbXmlId = result[0][0];
DateTime dbXMLDocDate = result[0][1];
if (dbXMLDocDate.isBefore(DateTime.parse(docDate!))) {
sql = """ ... """;
// print(sql);
await connection.query(sql);
sql = """ .... """;
currentJob['filesInserted']++;
await connection.query(sql);
} else {
sql = """ .... """;
await connection.query(sql);
}
}
} on PostgreSQLException catch (e) {
print('Exception during Insert in xml_files: $e');
exit(0);
} on SocketException catch (e) {
// пытаемся багу поймать
print('SocketException during Insert in xml_files: $e');
exit(0);
} on Exception catch (e) {
print('BaseException during Insert in xml_files: $e');
exit(0);
} catch (e) {
print("We should not reach this");
}
What I am getting on console:
aaa
Unhandled exception:
SocketException: Write failed (OS Error: An existing connection was forcibly closed by the remote host, errno = 10054), address = localhost, port = 51230
#0 _NativeSocket.write (dart:io-patch/socket_patch.dart:1182:34)
#1 _RawSocket.write (dart:io-patch/socket_patch.dart:1897:15)
#2 _Socket._write (dart:io-patch/socket_patch.dart:2334:18)
#3 _SocketStreamConsumer.write (dart:io-patch/socket_patch.dart:2082:26)
#4 _SocketStreamConsumer.addStream.<anonymous closure> (dart:io-patch/socket_patch.dart:2056:11)
#5 _RootZone.runUnaryGuarded (dart:async/zone.dart:1620:10)
#6 _BufferingStreamSubscription._sendData(dart:async/stream_impl.dart:341:11)
#7 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
#8 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:733:19)
#9 _StreamController._add (dart:async/stream_controller.dart:607:7)
#10 _StreamController.add (dart:async/stream_controller.dart:554:5)
#11 _StreamSinkImpl.add (dart:io/io_sink.dart:136:17)
#12 _Socket.add (dart:io-patch/socket_patch.dart:2181:38)
#13 Query.sendExtended (package:postgres/src/query.dart:98:12)
#14 _PostgreSQLConnectionStateIdle.processQuery (package:postgres/src/connection_fsm.dart:214:9)
#15 _PostgreSQLConnectionStateIdle.awake (package:postgres/srcconnection_fsm.dart:200:14)
#16 _PostgreSQLExecutionContextMixin._enqueue (package:postgres/srcconnection.dart:516:67)
#17 _PostgreSQLExecutionContextMixin._query (package:postgres/srcconnection.dart:460:15)
#18 _PostgreSQLExecutionContextMixin.query (package:postgres/srcconnection.dart:427:7)
#19 insertOrUpdateXmlFiles (package:data_loader/Servicesftp_service.dart:499:53)
#20 scanUnpackedFolder (package:data_loader/Services/ftp_service.dart:360:11)
<asynchronous suspension>
#21 unpackArchive (package:data_loader/Services/ftp_service.dart:320:6)
<asynchronous suspension>
#22 downloadArchive (package:data_loader/Services/ftp_service.dart:281:7)
<asynchronous suspension>
#23 runFtpParsingOrOnlyUnpackArchives (package:data_loader/Services/ftp_service.dart:736:5)
<asynchronous suspension>
#24 choiceOfProcessingAction (package:data_loader/Services/ftp_service.dart:658:9)
<asynchronous suspension>
#25 startNewJob (package:data_loader/Services/ftp_service.dart:762:5)
<asynchronous suspension>
#26 main.<anonymous closure> (file:///D:/code/zakupki/data_loader/bin/data_loader.dart:61:9)
<asynchronous suspension>
#27 Alfred._incomingRequest (package:alfred/src/alfred.dart:345:15)
<asynchronous suspension>
#28 _QueuedFuture.execute (package:queue/src/dart_queue_base.dart:26:16)
<asynchronous suspension>
I am seeing on console: aaa but do not see bbb and try-catch do not handle an Exception between them.
Full code: https://gist.github.com/bubnenkoff/7377f735671aacd624371a14151856f4

Solved though chat so this is a resume:
There have been created an issue for this problem here: https://github.com/isoos/postgresql-dart/issues/23
Initial testing shows that it might be because the package are using a synchronously completer, which is really a great way to get a lot of potential issues if you read the official documentation: https://api.dart.dev/stable/2.15.1/dart-async/Completer/Completer.sync.html
If the Completer is changed to a normal asynchronously completer, it is possible to catch the exception from the question.
The issue might be solved in another way but the conclusion is that the problem (with not being able to catch the exceptions, not the exceptions themself) is very likely in the postgres package and should be fixed here.

Related

Flutter Unexpected end of input (at character 1)

How to fix this error
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception:
FormatException: Unexpected end of input (at character 1) E/flutter
(11841): E/flutter (11841): ^ E/flutter (11841): E/flutter (11841):
0 _ChunkedJsonParser.fail (dart:convert/runtime/libconvert_patch.dart:1357:5) E/flutter (11841):
1 _ChunkedJsonParser.close (dart:convert/runtime/libconvert_patch.dart:510:7) E/flutter (11841):
2 _parseJson (dart:convert/runtime/libconvert_patch.dart:30:10) E/flutter (11841): #3 JsonDecoder.convert
(dart:convert/json.dart:491:36) E/flutter (11841): #4
JsonCodec.decode (dart:convert/json.dart:149:41) E/flutter (11841): #5
storeSync (package:reborn_next_job02/Cache/syncApi.dart:19:29)
E/flutter (11841): E/flutter (11841): #6
_ListPageState.initState. (package:reborn_next_job02/ui/AssetRegisters.dart:54:9) E/flutter
(11841): #7 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter (11841): #8 _CustomZone.runUnary
(dart:async/zone.dart:1029:19) E/flutter (11841): #9
_CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7) E/flutter (11841): #10 _CustomZone.bindUnaryCallbackGuarded. (dart:async/zone.dart:968:26) E/flutter (11841): #11
_rootRunUnary (dart:async/zone.dart:1136:13) E/flutter (11841): #12 _CustomZone.runUnary (dart:async/zone.dart:1029:19) E/flutter (11841): #13 _CustomZone.bindUnaryCallback. (dart:async/zone.dart:952:26) E/flutter (11841): #14
_Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19) E/flutter (11841): #15 _Timer._handleMessage
(dart:isolate/runtime/libtimer_impl.dart:416:5) E/flutter (11841): #16
_RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
syncApi.dart
storeSync(String url, String token) async {
final response = await http.get(
'$url/v1.0/SyncDataTable',
headers: {'Authorization': 'Bearer $token'},
);
final jsonResponse = json.decode(response.body);
SyncModel model = SyncModel.fromJson(jsonResponse);
int length = model.data.length;
HelperSync().display()).elementAt(i)?.syn_ChangeSequence,
for (int i = 0; i < length; i++) {
if ((await HelperSync().display()).elementAt(i)?.syn_TableName == model.data[i].syn_TableName) {
if ((await HelperSync().display()).elementAt(i)?.syn_ChangeSequence != model.data[i].syn_ChangeSequence) {
switch (i) {
case 21:
{
await HelperDatabase1().storeRegister(url, token);
}
break;
}
}
}
}
}
"FormatException" errors are usually caused by encoding issues. To solve this issue, you can cast response.body as a HashMap to look for the resulting Map<String, dynamic> before decoding.
// final jsonResponse = json.decode(response.body); // we can skip
SyncModel model = SyncModel.fromJson(response.body as Map<String, dynamic>>);

How to run task in background even if the app is closed and get the latest result generated by the task and display it when app is opened?

I want to to create a step counter app in flutter so i used Flutter pedometer plugin and it worked perfectly, but i want to run this plugin every time to calculate user steps even if the main app is closed .
I found that i can use dart isolates to create a task that can run in another thread away from main thread and communicate between them through ports .
String _stepCountValue = '0';
ReceivePort _receivePort;
Isolate isolate;
iniState() {
super.initState();
_start();
}
void _start() async {
_receivePort = ReceivePort();
isolate = await Isolate.spawn(initPlatformState,
_receivePort.sendPort);
_receivePort.listen((data) {
print(data);
setState(() {
_stepCountValue = "$data";
});
}, onDone: () {
print("done!");
});
}
static void initPlatformState(SendPort sendPort) async {
Pedometer pedometer = new Pedometer();
pedometer.stepCountStream.listen((int stepCountValue) {
print("------------------> $stepCountValue");
sendPort.send(stepCountValue);
}, onError: (error){print(error);}, onDone: (){}, cancelOnError:
true);
}
I expect the output to be the number of user steps .
but i get that error
I/flutter (26151): ══╡ EXCEPTION CAUGHT BY SERVICES LIBRARY ╞══════════════════════════════════════════════════════════
I/flutter (26151): The following _CompileTimeError was thrown while activating platform stream on channel
I/flutter (26151): pedometer.eventChannel:
I/flutter (26151): error: native function 'Window_sendPlatformMessage' (4 arguments) cannot be found
I/flutter (26151): When the exception was thrown, this was the stack:
I/flutter (26151): #0 Window.sendPlatformMessage (dart:ui/window.dart:868:9)
I/flutter (26151): #1 BinaryMessages._sendPlatformMessage (package:flutter/src/services/platform_messages.dart:46:15)
I/flutter (26151): #2 BinaryMessages.send (package:flutter/src/services/platform_messages.dart:97:12)
I/flutter (26151): #3 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:295:50)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #4 EventChannel.receiveBroadcastStream.<anonymous closure> (package:flutter/src/services/platform_channel.dart:490:29)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #12 StepCounterState.initPlatformState (package:stepcounter/main.dart:59:30)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #13 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:303:17)
I/flutter (26151): #14 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)
I/flutter (26151): (elided 7 frames from package dart:async)

json.decode throws FormatException on nested double quote in json - dart

Below code snippet throws Format Exception in Flutter json decode, Any suggestion please?
import 'dart:async' show Future;
import 'dart:convert';
Future<String> readBooks() async {
String jsonString = '{"description":"As part of the "You Don’t Know JS" series","quantity":55}';
Map<String, dynamic> books = json.decode(jsonString);
return jsonString;
}
Format Exception:
2018-10-23 20:40:30.680 18115-18142/addon.com.bookshop E/flutter:
[ERROR:flutter/shell/common/shell.cc(181)] Dart Error: Unhandled
exception:
FormatException: Unexpected character (at character 26)
{"name":"As part of the "You Don’t Know JS" series","Age":55}
^
#0 _ChunkedJsonParser.fail (dart:convert/runtime/libconvert_patch.dart:1358:5)
#1 _ChunkedJsonParser.parse (dart:convert/runtime/libconvert_patch.dart:919:48)
#2 _parseJson (dart:convert/runtime/libconvert_patch.dart:29:10)
#3 JsonDecoder.convert (dart:convert/json.dart:540:36)
#4 JsonCodec.decode (dart:convert/json.dart:167:41)
#5 _MyHomePageState.readBooks (file:///E:/Me/TimePass/flutter/book_shop/lib/main.dart:58:39)
<asynchronous suspension>
#6 _MyHomePageState.build.<anonymous closure> (file:///E:/Me/TimePass/flutter/book_shop/lib/main.dart:48:39)
<asynchronous suspension>
#7 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:503:14)
#8 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:558:30)
#9 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
#10 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
#11 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
#12 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9)
#13 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
#14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
#15 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:143:19)
#16 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
#17 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
#18 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue
(package:flutter/src/gestures/binding.dart:64:7)
#19 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket
(package:flutter/src/gestures/binding.dart:48:7)
#20 _invoke1 (dart:ui/hooks.dart:142:13)
#21 _dispatchPointerDataPacket (dart:ui/hooks.dart:99:5)
That's just invalid JSON.
The inner quotes need to be escaped as \" to make your JSON valid.

type '(PlatformException) => void' is not a subtype of type '(Object) => FutureOr<dynamic> Flutter

I am using Event Channels in Flutter to return beacon data from Native SDK to Flutter. This was working fine until a recent Flutter upgrade.Now, I am getting the following error.
type '(PlatformException) => void' is not a subtype of type '(Object) => FutureOr<dynamic>
with the following stack trace:
#0 _registerErrorHandler (dart:async/async_error.dart:22:60)
#1 _BufferingStreamSubscription.onError (dart:async/stream_impl.dart:146:16)
#2 new _BufferingStreamSubscription (dart:async/stream_impl.dart:113:10)
#3 new _ControllerSubscription (dart:async/stream_controller.dart)
#4 new _BroadcastSubscription (dart:async/broadcast_stream_controller.dart)
#5 _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:212:46)
#6 _ControllerStream._createSubscription (dart:async/stream_controller.dart:817:19)
#7 _StreamImpl.listen (dart:async/stream_impl.dart:466:9)
#8 _MyHomePageState.initPlatformState.<anonymous closure>.<anonymous closure> (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:95:43)
#9 _RootZone.runUnary (dart:async/zone.dart:1381:54)
#10 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
#11 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45)
#12 Future._propagateToListeners (dart:async/future_impl.dart:662:32)
#13 Future._complete (dart:async/future_impl.dart:467:7)
#14 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#15 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart)
<asynchronous suspension>
#16 _MyHomePageState.initPlatformState.<anonymous closure> (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:89:24)
<asynchronous suspension>
#17 _RootZone.runUnary (dart:async/zone.dart:1381:54)
#18 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
#19 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45)
#20 Future._propagateToListeners (dart:async/future_impl.dart:662:32)
#21 Future._complete (dart:async/future_impl.dart:467:7)
#22 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#23 User_Profile.getUser (package:flutter_poc/Models/User.dart)
<asynchronous suspension>
#24 _MyHomePageState.initPlatformState (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:69:24)
<asynchronous suspension>
#25 _MyHomePageState.initState (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:52:5)
#26 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3734:58)
#27 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
#28 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
#29 Element.updateChild
This is my EventChannel implementation:
static const platform = const MethodChannel('samples.flutter.io/initialiseRanging');
static const stream =
const EventChannel('samples.flutter.io/ranging');
try {
await platform.invokeMethod('initialiseRanging').then((result){
print(result);
setState(() {
_currentValue = result;
});
stream.receiveBroadcastStream().listen(_onEvent, onError: _onError);
});
} on PlatformException catch (e) {
print( "{e.message}");
}
This is how the _onEvent and _onError functions are implemented.
void _onEvent(Object event) {
setState(() {
_currentValue = event.toString();
});
print(event);
}
void _onError(PlatformException error) {
print(error);
}
Any idea on why this could possible happen?
void _onError(PlatformException error) {
should be
void _onError(Object error) {
Even when you are only interested in PlatformException or even when this is the only exception that happened so far, doesn't mean there can't be others. The expected handler function needs to match the parameter type, instead of only the exceptions you expect.

dart upload file error: FormatException: Bad UTF-8 encoding 0xbf

Here is my server side dart code:
import 'dart:io';
import 'package:http_server/http_server.dart';
void main() {
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
server.listen((HttpRequest request) {
if (request.method.toLowerCase() == 'post' && request.uri.path == '/upload') {
HttpBodyHandler.processRequest(request).then((body) {
HttpBodyFileUpload fileUpload = body.body['file'];
File file = new File('aaa');
file.writeAsBytes(fileUpload.content, mode: FileMode.WRITE).then((_) {
request.response.close();
});
});
}
});
});
}
and my error is:
Unhandled exception:
Uncaught Error: FormatException: Bad UTF-8 encoding 0xbf
Stack Trace:
#0 _Utf8Decoder.convert (dart:convert/utf.dart:534)
#1 _Utf8ConversionSink.addSlice (dart:convert/string_conversion.dart:334)
#2 _Utf8ConversionSink.add (dart:convert/string_conversion.dart:330)
#3 _ConverterStreamEventSink.add (dart:convert/chunked_conversion.dart:89)
#4 _handleData (dart:async/stream_transformers.dart:119)
#5 _RootZone.runUnaryGuarded (dart:async/zone.dart:1020)
#6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341)
#7 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:270)
#8 _StreamController&&_SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:578)
#9 _StreamController._add (dart:async/stream_controller.dart:453)
#10 _StreamController.add (dart:async/stream_controller.dart:410)
#11 BoundMultipartStream._parse.reportData (package:mime/src/bound_multipart_stream.dart:161:34)
#12 BoundMultipartStream._parse (package:mime/src/bound_multipart_stream.dart:318:28)
#13 BoundMultipartStream.BoundMultipartStream.<anonymous closure>.<anonymous closure> (package:mime/src/bound_multipart_stream.dart:111:24)
#14 _RootZone.runUnaryGuarded (dart:async/zone.dart:1020)
#15 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341)
#16 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:270)
#17 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:122)
#18 _ForwardingStream._handleData (dart:async/stream_pipe.dart:86)
#19 _handleData (dart:async/stream_pipe.dart:154)
#20 _RootZone.runUnaryGuarded (dart:async/zone.dart:1020)
#21 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341)
#22 _DelayedData.perform (dart:async/stream_impl.dart:595)
#23 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:711)
#24 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:671)
#25 _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:41)
#26 _asyncRunCallback (dart:async/schedule_microtask.dart:48)
#27 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:126)
#0 _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:820)
#1 _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:41)
#2 _asyncRunCallback (dart:async/schedule_microtask.dart:48)
#3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:126)
Process finished with exit code 255
I used postman to make a post, I chose form-data and add a key called file, value is a txt file.
after send my post to dart server, i got this exception.
is there something wrong with the post ? or the dart code ?
I'm really new to dart, please help me out...
thank you.

Resources