Created
December 28, 2013 09:40
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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