From eeed95141e849ca611536fe2179e0a85340cdbe7 Mon Sep 17 00:00:00 2001 From: Gang Li Date: Wed, 20 Dec 2023 21:06:22 +0800 Subject: [PATCH] Rest Client: add json error handling for rest error --- src/main/webui/src/app/utils/RestClient.js | 27 +++++++++++-------- .../webui/src/app/utils/RestClient.test.js | 6 +++++ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/src/main/webui/src/app/utils/RestClient.js b/src/main/webui/src/app/utils/RestClient.js index 163fc65..dff6e32 100644 --- a/src/main/webui/src/app/utils/RestClient.js +++ b/src/main/webui/src/app/utils/RestClient.js @@ -14,6 +14,7 @@ * limitations under the License. */ +import {Utils} from "./AppUtils.js"; const httpCall = (url, method, headers={}, payload) => fetch(url, { method, @@ -35,13 +36,13 @@ const jsonRest ={ put: (url, payload) => httpCall(url, "PUT", {"Content-type": "application/json"}, JSON.stringify(payload)) }; -const logErrors = response => { - if(response.text()){ - response.text().then(error=>console.log(error)); - }else{ - console.log(`Something wrong: ${response.status} -> ${response.statusText}`); - } -}; +// const logErrors = response => { +// if(response.text()){ +// response.text().then(error=>console.log(error)); +// }else{ +// console.log(`Something wrong: ${response.status} -> ${response.statusText}`); +// } +// }; const BASE_API_PATH = "/api/admin/stores"; const storeAPIEndpoint = (pkgType, type, name) => `${BASE_API_PATH}/${pkgType}/${type}/${name}`; @@ -51,9 +52,13 @@ const handleResponse = async response => { const result = await response.json(); return {result, success: true}; } - const responseMsg = await response.text(); - if(responseMsg){ - return {success: false, error: {status: response.status, message: responseMsg}}; + try { + const responseData = await response.json(); + if(responseData){ + return {success: false, error: {status: response.status, message: responseData.error}}; + } + }catch(e) { + Utils.logMessage(e.type); } return {success: false, error: {status: response.status, message: response.statusText}}; }; @@ -123,4 +128,4 @@ const IndyRest = { -export {http, jsonRest, logErrors, IndyRest, BASE_API_PATH}; +export {IndyRest, BASE_API_PATH}; diff --git a/src/main/webui/src/app/utils/RestClient.test.js b/src/main/webui/src/app/utils/RestClient.test.js index 1cc6488..2f57c4b 100644 --- a/src/main/webui/src/app/utils/RestClient.test.js +++ b/src/main/webui/src/app/utils/RestClient.test.js @@ -42,4 +42,10 @@ describe('IndyRest test', () => { expect(result.success).toBe(false); expect(result.error).toEqual({status: 404, message: "Not Found"}); }); + it('Check get store: error with json body', async () => { + fetchMock.mock(`${BASE_API_PATH}/maven/remote/central`, {status: 500, body: JSON.stringify({error: "Mock internal error"})}); + const result = await IndyRest.storeRes.get("maven", "remote", "central"); + expect(result.success).toBe(false); + expect(result.error).toEqual({status: 500, message: "Mock internal error"}); + }); });