From b08132c72021936e8a05ccdc35585e8b71cdac6c Mon Sep 17 00:00:00 2001 From: iona5 Date: Sat, 10 Jan 2015 13:28:14 +0100 Subject: [PATCH] add error handling for individual devices, prevent crash if one device throws error * individual setups should run in a domain, so we can catch errors individually * add feature to README.md --- README.md | 2 ++ lib/main.js | 28 +++++++++++++++++++++++----- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 4e99f90..67cd515 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,8 @@ When this option is set, airsonos skips teh autodiscovery part and tries to conn specified in . A Sonos device is specified by its IP. Optionally you can set also its TCP port if the device is set to not use the default port (1400). +As long as airsonos is able to connect to at least one device, it will not end itself. + This is the syntax: ``` airsonos --devices SONOS1_IP[:SONOS1_PORT][,SONOS2_IP[:SONOS2_PORT][,...]] diff --git a/lib/main.js b/lib/main.js index 3973ecb..4d7482e 100644 --- a/lib/main.js +++ b/lib/main.js @@ -110,17 +110,35 @@ if (flags.get('version')) { diag(); } else if (flags.get('devices').length > 0) { - var useDevices = flags.get('devices'); - for (var i = 0; i < useDevices.length; i++) { - var ipPortSplit = useDevices[i].split(':'); + + var deviceArguments = flags.get('devices'); + for(var i = 0; i < deviceArguments.length; i++) { + + var deviceArg = deviceArguments[i]; + + // set up a domain to catch errors from setting up individual + // devices. For example it catches the timeout when non-existing IPs + // are entered. + var setupDomain = require('domain').create(); + setupDomain.on('error', function(err) { + console.error('Error on setting up device "' + deviceArg + '": ' + err); + }); + var sonosDevice; + + // Check if the argument contains a port specifier + var ipPortSplit = deviceArg.split(':'); if (ipPortSplit.length > 1) { sonosDevice = new sonos.Sonos(ipPortSplit[0], ipPortSplit[1]); } else { - sonosDevice = new sonos.Sonos(useDevices[i]); + sonosDevice = new sonos.Sonos(deviceArg); } - setupSonos(sonosDevice, 'Sonos' + i); + // run the setup in a domain so we can catch errors for each device + // individually: + setupDomain.run(function() { + setupSonos(sonosDevice); + }); } } else {