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

66 lines
2.1 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;
}
class ServiceError extends Error {
constructor(statusCode = 500) {
super(defaultErrorMessage);
this.name = 'ServiceError';
this.statusCode = statusCode;
}
}
export class AuthenticationError extends Error {
constructor(statusCode, body) {
super('Authentication required');
this.name = 'AuthenticationError';
this.statusCode = statusCode;
this.body = body;
}
}
export class ForbiddenError extends Error {
constructor(statusCode, body) {
super('You cannot perform this action');
this.name = 'ForbiddenError';
this.statusCode = statusCode;
this.body = body;
}
}
export function throwIfNotSuccess(response) {
2016-11-10 14:26:24 +01:00
if (!response.ok) {
if (response.status === 401) {
return new Promise((resolve, reject) => {
response.json().then(body => reject(new AuthenticationError(response.status, body)));
});
} else if (response.status === 403) {
return new Promise((resolve, reject) => {
response.json().then(body => reject(new ForbiddenError(response.status, body)));
});
} else if (response.status > 399 && response.status < 499) {
2016-11-10 14:26:24 +01:00
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 ServiceError(response.status));
2016-11-10 14:26:24 +01:00
}
}
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',
};