From a82cc57f836b9a31b4c1c78d59148654852e4a05 Mon Sep 17 00:00:00 2001 From: Nolan Lawson Date: Sat, 24 Feb 2018 19:25:33 -0800 Subject: [PATCH] fix ajax error handling --- routes/_actions/favorite.js | 5 +---- routes/_utils/ajax.js | 19 ++++++++++++++++--- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/routes/_actions/favorite.js b/routes/_actions/favorite.js index 8683914..60959e3 100644 --- a/routes/_actions/favorite.js +++ b/routes/_actions/favorite.js @@ -11,12 +11,9 @@ export async function setFavorited (statusId, favorited) { let instanceName = store.get('currentInstance') let accessToken = store.get('accessToken') try { - let result = await (favorited + await (favorited ? favoriteStatus(instanceName, accessToken, statusId) : unfavoriteStatus(instanceName, accessToken, statusId)) - if (result.error) { - throw new Error(result.error) - } await database.setStatusFavorited(instanceName, statusId, favorited) let statusModifications = store.get('statusModifications') let currentStatusModifications = statusModifications[instanceName] = diff --git a/routes/_utils/ajax.js b/routes/_utils/ajax.js index 85ad71a..162f586 100644 --- a/routes/_utils/ajax.js +++ b/routes/_utils/ajax.js @@ -7,6 +7,17 @@ function fetchWithTimeout (url, options) { }) } +async function throwErrorIfInvalidResponse(response) { + let json = await response.json() + if (response.status >= 200 && response.status < 300) { + return json + } + if (json && json.error) { + throw new Error(response.status + ': ' + json.error) + } + throw new Error('Request failed: ' + response.status) +} + async function _post (url, body, headers, timeout) { let fetchFunc = timeout ? fetchWithTimeout : fetch let opts = { @@ -23,17 +34,19 @@ async function _post (url, body, headers, timeout) { 'Accept': 'application/json' }) } - return (await fetchFunc(url, opts)).json() + let response = await fetchFunc(url, opts) + return throwErrorIfInvalidResponse(response) } async function _get (url, headers, timeout) { let fetchFunc = timeout ? fetchWithTimeout : fetch - return (await fetchFunc(url, { + let response = await fetchFunc(url, { method: 'GET', headers: Object.assign(headers, { 'Accept': 'application/json' }) - })).json() + }) + return throwErrorIfInvalidResponse(response) } export async function post (url, body, headers = {}) {