From d0b8b605db93c51b5ce2501a482c57432b45bfa6 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sat, 30 Jan 2021 12:33:29 -0500 Subject: Add note errors (#1329) * Update _addAnkiNote to track errors * Change comparison * Update anki note adding to show errors * Fix template * Show errors when Anki card creation behaves unexpectedly * Update some errors related to anki media injection * Update addAnkiNote error handling * Improve Anki errors * Simplify error messages related to template rendering --- ext/bg/js/anki.js | 53 ++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 40 insertions(+), 13 deletions(-) (limited to 'ext/bg/js/anki.js') diff --git a/ext/bg/js/anki.js b/ext/bg/js/anki.js index 68d9fc43..251e0e0c 100644 --- a/ext/bg/js/anki.js +++ b/ext/bg/js/anki.js @@ -162,22 +162,49 @@ class AnkiConnect { } async _invoke(action, params) { - const response = await fetch(this._server, { - method: 'POST', - mode: 'cors', - cache: 'default', - credentials: 'omit', - redirect: 'follow', - referrerPolicy: 'no-referrer', - body: JSON.stringify({action, params, version: this._localVersion}) - }); - const result = await response.json(); + let response; + try { + response = await fetch(this._server, { + method: 'POST', + mode: 'cors', + cache: 'default', + credentials: 'omit', + redirect: 'follow', + referrerPolicy: 'no-referrer', + body: JSON.stringify({action, params, version: this._localVersion}) + }); + } catch (e) { + const error = new Error('Anki connection failure'); + error.data = {action, params}; + throw error; + } + + if (!response.ok) { + const error = new Error(`Anki connection error: ${response.status}`); + error.data = {action, params, status: response.status}; + throw error; + } + + let responseText = null; + let result; + try { + responseText = await response.text(); + result = JSON.parse(responseText); + } catch (e) { + const error = new Error('Invalid Anki response'); + error.data = {action, params, status: response.status, responseText}; + throw error; + } + if (isObject(result)) { - const error = result.error; - if (typeof error !== 'undefined') { - throw new Error(`AnkiConnect error: ${error}`); + const apiError = result.error; + if (typeof apiError !== 'undefined') { + const error = new Error(`Anki error: ${apiError}`); + error.data = {action, params, status: response.status, apiError}; + throw error; } } + return result; } -- cgit v1.2.3