From 8e3d06b084e3f127febf4d54234a6def5a0b4e3f Mon Sep 17 00:00:00 2001 From: grandeljay Date: Sat, 26 Feb 2022 23:14:10 +0100 Subject: [PATCH] Improve fetch error handling --- src/assets/js/default.js | 57 ++++++++++++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/src/assets/js/default.js b/src/assets/js/default.js index 437218e6..94ae1c2c 100644 --- a/src/assets/js/default.js +++ b/src/assets/js/default.js @@ -49,10 +49,6 @@ $(function() { } } $.fn.api.settings.onFailure = function(response, element, xhr) { - console.log(response); - console.log(element); - console.log(xhr); - if ('string' === typeof response) { response = response.replace('
', ''); } @@ -72,10 +68,6 @@ $(function() { .modal('show'); } $.fn.api.settings.onError = function(response, element, xhr) { - console.log(response); - console.log(element); - console.log(xhr); - if ('string' === typeof response) { response = response.replace('
', ''); } @@ -101,3 +93,52 @@ $(function() { $.fn.toast.settings.minDisplayTime = 3000; $.fn.toast.settings.showProgress = true; }); + +/** + * Functions + */ +function handleFetchError(response) { + if (!response.ok) { + console.log('handleFetchError'); + console.log(response); + + showError(response.statusText); + throw Error(response.statusText); + } + + return response; +} + +function handleFetchResponse(response) { + var isText = response.headers.get('content-type')?.includes('text/html'); + var isJSON = response.headers.get('content-type')?.includes('application/json'); + + if (isText) { + return response.text() + .then(function(text) { + if (text.toLowerCase().includes('error') || text.toLowerCase().includes('exception')) { + showError(text); + } + }) + } else if (isJSON) { + return response.json(); + } +} + +function showError(error) { + error = error.replace('
', ''); + + $('body') + .modal({ + title: 'Error', + content: error, + class: '', + actions: [ + { + text: 'Thanks for nothing', + class: 'primary' + } + ] + }) + .modal('show'); +}