Skip to content
This repository has been archived by the owner on Apr 17, 2023. It is now read-only.

Commit

Permalink
refactor(Rest): if retries are exceeded throw the last error
Browse files Browse the repository at this point in the history
  • Loading branch information
didinele committed Jan 21, 2022
1 parent 560dbb7 commit 1395162
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
3 changes: 1 addition & 2 deletions libs/rest/src/Error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ export const CordisRestError = makeCordisError(
{
retryLimitExceeded: (request: string, attempts: number) => `Tried to "${request}" for ${attempts} times but all of them failed`,
mutexLock: (route: string) => `A mutex for the "${route}" bucket locked up but was told to not wait`,
rateLimited: (request: string) => `A ratelimit was hit/prevented while "${request}"`,
internal: (request: string) => `Discord raised an internal error on "${request}"`
rateLimited: (request: string) => `A ratelimit was hit/prevented while "${request}"`
}
);

Expand Down
24 changes: 16 additions & 8 deletions libs/rest/src/struct/Rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,8 @@ export class Rest extends EventEmitter {
const isGet = options.method.toLowerCase() === 'get';
const shouldCache = options.cache && isGet;

let rejected: Promise<never>;

for (let retries = 0; retries <= this.retries; retries++) {
try {
if (shouldCache && this.cache.has(options.path)) {
Expand Down Expand Up @@ -273,21 +275,27 @@ export class Rest extends EventEmitter {
const isRatelimit = e instanceof CordisRestError && e.code === 'rateLimited';
isRetryAfterRatelimit = isRatelimit;

if (
e instanceof HTTPError ||
e.name === 'AbortError' ||
(isRatelimit && !options.retryAfterRatelimit)
) {
if (e.name === 'AbortError') {
return Promise.reject(e);
}

if (e instanceof CordisRestError && e.code === 'internal') {
await halt(1000);
if (isRatelimit && !options.retryAfterRatelimit) {
return Promise.reject(e);
}

if (e instanceof HTTPError) {
if (e.response.status >= 500 && e.response.status < 600) {
await halt(1000);
} else {
return Promise.reject(e);
}
}

rejected = Promise.reject(e);
}
}

return Promise.reject(new CordisRestError('retryLimitExceeded', `${options.method.toUpperCase()} ${options.path}`, this.retries));
return rejected!;
}

/**
Expand Down

0 comments on commit 1395162

Please sign in to comment.