From 3d208cf7d92c806e60d04571121b9cceb9b0cd9e Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Tue, 13 Jun 2023 00:14:01 +0200 Subject: Fixed error handling after network code rework --- lib/api.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'lib/api.js') diff --git a/lib/api.js b/lib/api.js index 9f9fc3e..040b477 100644 --- a/lib/api.js +++ b/lib/api.js @@ -33,7 +33,6 @@ async function queue_processor() { const before = new Date(); await send_this(queue.dequeue().element); const duration = new Date() - before; - console.log(before.toISOString(), new Date().toISOString(), duration); if (duration < 400) { // 333 should work, but 400 should still allow some manual requests to go through during development await sleep(400 - duration); } @@ -90,10 +89,11 @@ async function send_this(data) { } fs.writeFileSync('log', JSON.stringify({event: 'send', date: new Date(), data: data}) + '\n', {flag: 'a+'}); let response = await fetch(`https://api.spacetraders.io/v2${data.request.endpoint}`, options); - if (response.ok) { + try { response = await response.json(); switch(response.error?.code) { //case 401: // TODO 401 means a server reset happened + // TODO reject all promises in queue // close database file // rm database file // logrotate @@ -103,17 +103,17 @@ async function send_this(data) { backoffSeconds = response.error.data.retryAfter; queue.enqueue(data, 1); break; - default: // no error! - fs.writeFileSync('log', JSON.stringify({event: 'response', date: new Date(), data: response}) + '\n', {flag: 'a+'}); - return data.resolve(response); - } - } else { - fs.writeFileSync('log', JSON.stringify({event: 'error', date: new Date(), data: response}) + '\n', {flag: 'a+'}); - switch(response.cause?.code) { case 503: // 503 means maintenance mode, let's hold back for 1 minute backoffSeconds = 60; queue.enqueue(data, 1); break; + default: // no error! + fs.writeFileSync('log', JSON.stringify({event: 'response', date: new Date(), data: response}) + '\n', {flag: 'a+'}); + return data.resolve(response); + } + } catch (err) { + fs.writeFileSync('log', JSON.stringify({event: 'error', date: new Date(), data: err}) + '\n', {flag: 'a+'}); + switch(err.cause?.code) { case 'EAI_AGAIN': // DNS lookup timed out error, let's hold back for 5 seconds backoffSeconds = 5; queue.enqueue(data, 1); -- cgit v1.2.3