From fa8c1ba4d02239116e56eebe6496fd90a1f8d36b Mon Sep 17 00:00:00 2001 From: Mozafar Haider Date: Tue, 12 Dec 2023 15:29:46 +0000 Subject: [PATCH] refactor: implement code review comments to make the api.request method more resilient --- src/api.js | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/api.js b/src/api.js index cc15901..5f92054 100644 --- a/src/api.js +++ b/src/api.js @@ -13,15 +13,22 @@ class Api { credentials: 'include', redirect: 'manual', }).then(async (res) => { - if (res.type === 'opaqueredirect') { - throw { - message: i18n.t( - 'Your session has expired. Please refresh the page and login before trying again.' - ), + let errorBody + try { + if (res.type === 'opaqueredirect') { + errorBody = { + message: i18n.t( + 'Your session has expired. Please refresh the page and login before trying again.' + ), + } + } else if (res.status < 200 || res.status >= 300) { + errorBody = await res.json() } + } catch (err) { + throw new Error(i18n.t('An unexpected error occurred')) } - if (res.status < 200 || res.status >= 300) { - const errorBody = await res.json() + + if (errorBody) { throw errorBody } return res