1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-10-18 20:09:08 +02:00
unleash.unleash/frontend/src/data/helper.js

32 lines
1.0 KiB
JavaScript
Raw Normal View History

2016-11-10 14:26:24 +01:00
const defaultErrorMessage = 'Unexptected exception when talking to unleash-api';
function extractJoiMsg(body) {
2017-08-28 21:40:44 +02:00
return body.details.length > 0 ? body.details[0].message : defaultErrorMessage;
}
function extractLegacyMsg(body) {
return body && body.length > 0 ? body[0].msg : defaultErrorMessage;
}
export function throwIfNotSuccess(response) {
2016-11-10 14:26:24 +01:00
if (!response.ok) {
if (response.status > 399 && response.status < 404) {
return new Promise((resolve, reject) => {
response.json().then(body => {
2017-08-28 21:40:44 +02:00
const errorMsg = body && body.isJoi ? extractJoiMsg(body) : extractLegacyMsg(body);
2016-11-10 14:26:24 +01:00
let error = new Error(errorMsg);
error.statusCode = response.status;
reject(error);
});
});
} else {
return Promise.reject(new Error(defaultErrorMessage));
}
}
return Promise.resolve(response);
}
2016-11-10 14:26:24 +01:00
export const headers = {
Accept: 'application/json',
2016-11-10 14:26:24 +01:00
'Content-Type': 'application/json',
};