Skip to content

Instantly share code, notes, and snippets.

@ThomasLocke
Created December 28, 2013 09:40
Show Gist options
  • Save ThomasLocke/8157769 to your computer and use it in GitHub Desktop.
Save ThomasLocke/8157769 to your computer and use it in GitHub Desktop.
Trying to harden client.getUrl() in Dart, so it never crashes my HTTP server and never completes with an error.
Future getTag() {
final Completer c = new Completer();
final HttpClient client = new HttpClient();
client.getUrl(Uri.parse(tagUrl))
.then((HttpClientRequest request) {
return request.close();
})
.catchError((e) {
// If the tagUrl server is down, we catch and log it here.
log('MetaData.getTag() -> client.getUrl() failed to establish connection ${e}');
})
.then((HttpClientResponse response) {
// It seems this null check is necessary, in case the connection failed. If I don't
// check for null, I end up trying to access stuff in the null response object.
if(response != null) {
switch(response.statusCode) {
case 200:
log('MetaData.getTag() -> client.getUrl() ${tagUrl} fetched OK');
response.listen((value) {
try {
tag = LATIN1.decode(value).trim();
} catch(e) {
// I feel I must catch decoding errors here, but it seems somewhat excessive
// with a "massive" try-catch block.
log('${e} - ${this}');
tag = null;
}
}, onError: (e) {
// Catch stream errors and drain the response. I've no idea what would trigger
// this, but better safe than sorry I guess.
response.drain();
log('${e} - ${this}');
});
break;
default:
response.drain();
log('MetaData.getTag() -> client.getUrl() failed with status code ${response.statusCode} - ${this}');
}
}
})
.catchError((e) {
log('${e} - ${this}');
})
.whenComplete(() {
// Complete with success, no matter what happened above.
c.complete();
});
// This client.close() call seems to be OK , even if the connection fails. I'm not sure
// where else to put it. Is it even necessary?
client.close();
return c.future;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment