From 55058b8b34a5f1a082d4f0b0f2cea1e5e591e07f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Daubensch=C3=BCtz?= Date: Fri, 17 Jul 2015 16:44:24 +0200 Subject: [PATCH] fix form error handling --- js/components/ascribe_forms/form.js | 1 + js/utils/requests.js | 42 +++++++++++++++++++---------- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/js/components/ascribe_forms/form.js b/js/components/ascribe_forms/form.js index ecbd17de..87f26cb3 100644 --- a/js/components/ascribe_forms/form.js +++ b/js/components/ascribe_forms/form.js @@ -80,6 +80,7 @@ let Form = React.createClass({ this.setState({edited: false, submitted: false}); }, handleError(err){ + console.log(err); if (err.json) { for (var input in err.json.errors){ if (this.refs && this.refs[input] && this.refs[input].state) { diff --git a/js/utils/requests.js b/js/utils/requests.js index ab64d635..8494a90f 100644 --- a/js/utils/requests.js +++ b/js/utils/requests.js @@ -20,21 +20,36 @@ class Requests { unpackResponse(response) { if (response.status >= 500) { throw new Error(response.status + ' - ' + response.statusText + ' - on URL:' + response.url); - } else if(response.status >= 400) { - throw new Error(response.status + ' - ' + response.statusText + ' - on URL:' + response.url); } - return response.text(); - } - customJSONparse(responseText) { - // If the responses' body does not contain any data, - // fetch will resolve responseText to the string 'None'. - // If this is the case, we can not try to parse it as JSON. - if(responseText !== 'None') { - return JSON.parse(responseText); - } else { - return {}; - } + return new Promise((resolve, reject) => { + response.text() + .then((responseText) => { + // If the responses' body does not contain any data, + // fetch will resolve responseText to the string 'None'. + // If this is the case, we can not try to parse it as JSON. + if(responseText !== 'None') { + let body = JSON.parse(responseText); + + if(body && body.errors) { + let error = new Error('Form Error'); + error.json = body; + reject(error); + } else { + resolve(body); + } + + } else { + if(response.status >= 400) { + reject(new Error(response.status + ' - ' + response.statusText + ' - on URL:' + response.url)); + } else { + resolve({}); + } + } + }).catch((err) => { + reject(err); + }); + }); } handleError(err) { @@ -100,7 +115,6 @@ class Requests { return fetch(url, merged) .then(this.unpackResponse) - .then(this.customJSONparse) .catch(this.handleError); }