Better error handling

This commit is contained in:
Eden Kirin
2023-04-23 10:03:50 +02:00
parent 6a64709d17
commit fb6d1276e6
2 changed files with 69 additions and 4 deletions

View File

@ -1,3 +1,13 @@
class ValidationError extends Error {
constructor(message) {
if (!message) {
message = "ValidationError";
}
super(message);
this.name = "ValidationError";
}
}
class PlayerNotFoundError extends Error {
constructor(message) {
if (!message) {
@ -65,6 +75,10 @@ class FairHopper {
headers: this.defaultHeaders,
body: JSON.stringify(payload),
});
switch (r.status) {
case 422:
throw new ValidationError();
}
return await r.json();
}
@ -84,6 +98,8 @@ class FairHopper {
throw new PlayerInactiveError();
case 404:
throw new PlayerNotFoundError();
case 422:
throw new ValidationError();
}
return await r.json();
}
@ -117,6 +133,8 @@ class FairHopper {
throw new PlayerNotFoundError();
case 409:
throw new PositionError();
case 422:
throw new ValidationError();
}
return await r.json();
}
@ -128,6 +146,17 @@ class FairHopper {
return await r.json();
}
async getProduct(productId) {
const r = await fetch(this.formatUrl(`/products/${productId}`), {
headers: this.defaultHeaders,
});
switch (r.status) {
case 422:
throw new ValidationError();
}
return await r.json();
}
async purchaseProduct(playerId, productId) {
const url = this.formatUrl(`/player/${playerId}/product/purchase`);
const postData = {
@ -145,6 +174,8 @@ class FairHopper {
throw new PlayerNotFoundError();
case 409:
throw new PositionError();
case 422:
throw new ValidationError();
}
return await r.json();
}