Our API server returns JSON data with error responses. I could not find a standard way of handling JSON data on error handling methods. my current solution is this. It is working, but I want to handle errors in catch() method not in then();
let url = 'http://localhost:8080';
let data = {'field': 'value'};
fetch(url, {
method: 'PUT',
body: JSON.stringify(data),
credentials: 'same-origin',
mode: 'cors',
headers: {
'content-type': 'application/json',
'accept': 'application/json'
}
})
.then(res => {
if (res.status == 400) {
return res.json();
} else if (!res.ok) {
throw (res);
} else {
return res.json();
}
}).then(data => {
if (data.status == 400) {
throw (data);
}
return (data);
}).catch(err => {
if (err.status == 400) {
throw this.handleError(err);
} else {
throw new Error(`HTTP Error ${err.status}`);
}
});
this is an example of JSON response from server.
{
"parameters": {
"type": {
"isEmpty": "Field is required and cannot be empty"
},
"from": {
"isEmpty": "Field is required and cannot be empty"
},
"to": {
"isEmpty": "Field is required and cannot be empty"
}
},
"title": "Invalid parameter",
"type": "/api/doc/invalid-parameter",
"status": 400,
"detail": "Invalid parameter"
}
return Promise.reject(res.json())if res.status == 400