From 740b125a45d531535d911dc663286fd8fa02e7af Mon Sep 17 00:00:00 2001 From: Jonathan Cremin Date: Fri, 5 Dec 2014 20:44:10 +0000 Subject: [PATCH] Handle search failures better --- lib/services/itunes.js | 3 +-- routes/search.js | 25 +++++++++++++++++++------ routes/share.js | 1 - 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/lib/services/itunes.js b/lib/services/itunes.js index 407f94c..20cf8dd 100644 --- a/lib/services/itunes.js +++ b/lib/services/itunes.js @@ -19,11 +19,10 @@ module.exports.lookupId = function(id, type) { request.get(apiRoot + path, function(res) { var data = JSON.parse(res.text); - if (!data.results || !data.results[0] || !data.results[0].collectionId) { + if (!data.results || data.resultCount == 0 || !data.results[0].collectionId) { var error = new Error("Not Found"); error.status = 404; deferred.reject(error); - return; } else { var result = data.results[0]; diff --git a/routes/search.js b/routes/search.js index 04bcd86..48d5d50 100644 --- a/routes/search.js +++ b/routes/search.js @@ -14,6 +14,7 @@ require("fs").readdirSync(path.join(__dirname, "..", "lib", "services")).forEach module.exports = function(req, res) { var url = parse(req.body.url); + var searching = false; if (!url.host) { req.flash('search-error', 'Paste a music link above to find and share the matches'); @@ -24,17 +25,29 @@ module.exports = function(req, res) { for (var id in services) { var matched = services[id].match(req.body.url); if (matched) { - services[id].parseUrl(req.body.url).then(function(result) { + searching = true; + Q.timeout(services[id].parseUrl(req.body.url), 5000).then(function(result) { if (!result.id) { req.flash('search-error', 'No match found for this link'); res.redirect('/'); } res.redirect("/" + id + "/" + result.type + "/" + result.id); - }) - return; + }, function(error) { + if (error.code == "ETIMEDOUT") { + error = new Error("Error talking to music service"); + error.status = "502"; + } else if (!error.status) { + error = new Error("An unexpected error happenend"); + error.status = 500; + } + next(error); + }); + + break; } } - - req.flash('search-error', 'No match found for this link'); - res.redirect('/'); + if (!searching) { + req.flash('search-error', 'No match found for this link'); + res.redirect('/'); + } }; diff --git a/routes/share.js b/routes/share.js index e2466e6..7b70a7d 100644 --- a/routes/share.js +++ b/routes/share.js @@ -61,7 +61,6 @@ module.exports = function(req, res, next) { res.render(type, {page: type, items: items}); }); }, function(error) { - console.log(error) if (error.code == "ETIMEDOUT") { error = new Error("Error talking to music service"); error.status = "502";