2016-11-10 14:26:24 +01:00
|
|
|
const defaultErrorMessage = 'Unexptected exception when talking to unleash-api';
|
|
|
|
|
2017-08-28 19:15:47 +02:00
|
|
|
function extractJoiMsg(body) {
|
|
|
|
return body.details.length > 0
|
|
|
|
? body.details[0].message
|
|
|
|
: defaultErrorMessage;
|
2016-12-17 16:47:16 +01:00
|
|
|
}
|
2017-08-28 19:15:47 +02:00
|
|
|
function extractLegacyMsg(body) {
|
2016-12-17 16:47:16 +01:00
|
|
|
return body && body.length > 0 ? body[0].msg : defaultErrorMessage;
|
|
|
|
}
|
|
|
|
|
2017-08-28 19:15:47 +02:00
|
|
|
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 19:15:47 +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);
|
2017-08-28 19:15:47 +02:00
|
|
|
}
|
2016-11-10 14:26:24 +01:00
|
|
|
|
|
|
|
export const headers = {
|
2017-08-28 19:15:47 +02:00
|
|
|
Accept: 'application/json',
|
2016-11-10 14:26:24 +01:00
|
|
|
'Content-Type': 'application/json',
|
|
|
|
};
|