context.setLineDash() works in Chrome, but in FireFox 18.0.1 results in
TypeError: this.setLineDash is not a function
deep in the bootstrap.dart.js file.
Even if I use this function
void setLineDashCatch(var ctx,var param) {
try {
ctx.setLineDash(param);
} on Exception catch (e) {
log('SetLineDash exception');
}
}
The exception is not caught, and the method is aborted.
What is the best way to avoid the method being aborted?
You don't get the log because it is not an Exception that is thrown. It is rather a NoSuchMethodError. The following code should work :
void setLineDashCatch(var ctx,var param) {
try {
ctx.setLineDash(param);
} on NoSuchMethodError catch (e) {
print('SetLineDash exception');
}
}
Related
following code as docs mention:
try {
breedMoreLlamas1();
} on OutOfLlamasException {
// A specific exception
buyMoreLlamas();
} on Exception catch (e) {
// Anything else that is an exception
print('Unknown exception: $e');
} catch (e) {
// No specified type, handles all
print('Something really unknown: $e');
}
void breedMoreLlamas1() {
print('buyMoreLlamas_1');
throw Exception;
}
I get buyMoreLlamas_1 and the message Something really unknown: Exception
Shouldn't be : Unknown exception: Exception
Any suggestion?
If I have nested async* streams, exceptions do not appear to be catchable, which is counterintuitive.
An example:
void main() {
getString().listen(print);
}
Stream<String> getString() async* {
try {
yield* asyncStarError();
yield await asyncError();
} catch (err) {
yield 'Crash';
}
}
Stream<String> asyncStarError() async* {
throw Exception('A Stream error happened');
}
Future<String> asyncError() async {
throw Exception('A Future error happened');
}
This outputs:
Uncaught Error: Exception: A Stream error happened
Crash
So the exception thrown by asyncStarError is not caught, while the Future is caught as expected. Can anyone explain why?
You can observe the behaviour in dartpad: https://dartpad.dartlang.org
The yield* forwards all events from the stream it yields, including errors.
So, asyncStarError() produces a stream with an error event, and yield* forwards that error to the stream returned by getString, and then the getString.listen(print); does not add a handler so the error becomes uncaught.
(I'm guessing you're running this in a browser since that uncaught error doesn't crash the program.)
After that, the yield await asyncError() never yield anything. The await asyncError() itself throws, before reaching the yield, and that error is then caught by the catch which yields crash.
If you want to catch the errors of a stream, you need to actually look at the events, not just use yield* to forward them all blindly, including error events.
For example:
await for (var _ in asyncStarError()) {
// Wohoo, event!
}
would make the error from the asyncStarError stream an error at the loop. It would then be caught and you'd print "Crash".
TL;DR: The yield* operation forwards error events, it doesn't raise them locally.
Since yield * forwards them like #lrn said, you can catch them in main just fine. Or wherever you are consuming them.
void main() {
getString().listen(print).onError((e) => print('error caught: $e'));
}
Stream<String> getString() async* {
try {
yield* asyncStarError();
yield await asyncError();
} catch (err) {
yield 'Crash';
}
}
Stream<String> asyncStarError() async* {
throw Exception('A Stream error happened');
}
Future<String> asyncError() async {
throw Exception('A Future error happened');
}
this prints:
error caught: Exception: A Stream error happened
Crash
The difference is that async generator (async*) exceptions cannot be caught by surrounding it with try/catch.
Instead, you should use the callback handleError to achieve the behaviour you are looking for.
To go further, you may be interested in using runZonedGuarded.
I have written a simple command line tool in dart that watches changes in a directory if a directory does not exits I get FileSystemsException.
I have tried to handle it using try and catch clause. When the exception occurs the code in catch clause is not executed
try {
watcher.events.listen((event) {
if (event.type == ChangeType.ADD) {
print("THE FILE WAS ADDED");
print(event.path);
} else if (event.type == ChangeType.MODIFY) {
print("THE FILE WAS MODIFIED");
print(event.path);
} else {
print("THE FILE WAS REMOVED");
print(event.path);
}
});
} on FileSystemException {
print("Exception Occurs");
}
I expect the console to print "Exception Occurs"
There are two possibilities:
The exception is happening outside this block (maybe where the watcher is constructed?)
The exception is an unhandled async exception. This might be coming from either the Stream or it might be getting fired from some other Future, like perhaps the ready Future.
You can add handlers for the async exceptions like this:
try {
// If this is in an `async` method, use `await` within the try block
await watcher.ready;
// Otherwise add a error handler on the Future
watcher.ready.catchError((e) {
print('Exception in the ready Future');
});
watcher.events.listen((event) {
...
}, onError: (e) {
print('Exception in the Stream');
});
} on FileSystemException {
print("Exception Occurs");
}
My guess would be it's an error surfaced through the ready Future.
import 'dart:async';
void main() {
divide(1, 0).then((result) => print('1 / 0 = $result'))
.catchError((error) => print('Error occured during division: $error'));
}
Future<double> divide(int a, b) {
if (b == 0) {
throw new Exception('Division by zero');
}
return new Future.value(a/b);
}
Currently I am learning how to work with futures in Dart and I got stucked on such an easy example. My future throws exception when user tries to perform division by zero. However, .catchError doesn't handle my exception. I got unhandled exception with a stack trace instead. I'm pretty sure that I am missing something obvious but can't understand what exactly.
As I understand, there is another way to handle error:
divide(1, 0).then((result) => print('1 / 0 = $result'),
onError: (error) => print('Error occured during division: $error'));
to use named optional argument - onError. Doing like this still leads to unhandled exception.
I would like to clarify one more thing. Am I right? - The only difference between these 2 approaches is that .catchError() also handles errors thrown by inner futures (futures that are called inside then() method of the outer future) while onError only catches errors thrown by the outer future?
Dmitry
Thank you.
Your error handling didn't work because the error is thrown in the synchronous part of your code. Just because the method returns a future doesn't mean everything in this method is async.
void main() {
try {
divide(1, 0)
.then((result) => print('1 / 0 = $result'));
} catch (error) {
print('Error occured during division: $error');
}
}
If you change your divide function like
Future<double> divide(int a, b) {
return new Future(() {
if (b == 0) {
throw new Exception('Division by zero');
}
return new Future.value(a / b);
});
}
you get an async error and your async error handling works.
An easier way is to use the new async/await
main() async {
try {
await divide(1, 0);
} catch(error){
print('Error occured during division: $error');
}
}
try at DartPad
and another advantage is this works in both cases.
Following the tutorial on DartWatch blog on using Google OAuth library. The question is how to handle: 'Access denied' error from Google ?
Here is my code example:
class Client
{
GoogleOAuth2 _auth;
Client()
{
_auth = new GoogleOAuth2(
'5xxxxxxxxxxxxxx.apps.googleusercontent.com', // Client ID
['openid', 'email', 'profile'],
tokenLoaded:oauthReady);
}
void doLogin()
{
// _auth.logout();
// _auth.token = null;
try
{
_auth.login();
}
on AuthException {
print('Access denied');
}
on Exception catch(exp)
{
print('Exception $exp occurred');
}
}
void oauthReady(Token token)
{
print('Token is: $token');
}
}
but I never hit catch block on any (!) exception. What I'm doing wrong ?
I'm using:
Dart Editor version 0.5.0_r21823
Dart SDK version 0.5.0.1_r21823
You never hit the catch block because auth.login is an asynchronous operation which returns a Future.
There is a great article on Future error handling on the dartlang.org website.
auth.login returns a Future immediately, but the work it does happens after control returns to the event loop (see my answer to another question for more on the event loop.)
Your code should look more like:
/// Returns a Future that completes to whether the login was successful.
Future<boolean> doLogin()
{
_auth.login()
.then((_) {
print("Success!");
return true;
}.catchError((e) {
print('Exception $e occurred.');
return false; // or throw the exception again.
}
}