Skip to content

Commit

Permalink
refactor(ecau): allow setting custom HTTP error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
ROpdebee committed Aug 8, 2022
1 parent d0958af commit d1813bb
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 15 deletions.
14 changes: 8 additions & 6 deletions src/lib/util/xhr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ export interface FetchProgress {
total: number;
}

// eslint-disable-next-line no-restricted-globals
/* eslint-disable no-restricted-globals */
type LimitedGMXHROptions = Omit<GM.Request, 'onload'|'onerror'|'onabort'|'ontimeout'|'onprogress'|'onreadystatechange'|'method'|'url'>;

export interface GMXHROptions extends LimitedGMXHROptions {
// eslint-disable-next-line no-restricted-globals
method?: GM.Request['method'];
progressCb?: (progress: FetchProgress) => void;

httpErrorMessages?: Record<number, string | undefined>;
}
/* eslint-enable no-restricted-globals */

export abstract class ResponseError extends CustomError {
public readonly url: string | URL;
Expand All @@ -35,9 +35,11 @@ export class HTTPResponseError extends ResponseError {
public readonly response: GM.Response<never>;

// eslint-disable-next-line no-restricted-globals
public constructor(url: string | URL, response: GM.Response<never>) {
public constructor(url: string | URL, response: GM.Response<never>, errorMessage?: string) {
/* istanbul ignore else: Should not happen */
if (response.statusText.trim()) {
if (errorMessage) {
super(url, errorMessage);
} else if (response.statusText.trim()) {
super(url, `HTTP error ${response.status}: ${response.statusText}`);
} else {
super(url, `HTTP error ${response.status}`);
Expand Down Expand Up @@ -73,7 +75,7 @@ export async function gmxhr(url: string | URL, options?: GMXHROptions): Promise<
...options,

onload: (resp) => {
if (resp.status >= 400) reject(new HTTPResponseError(url, resp));
if (resp.status >= 400) reject(new HTTPResponseError(url, resp, options?.httpErrorMessages?.[resp.status]));
else resolve(resp);
},
onerror: () => { reject(new NetworkError(url)); },
Expand Down
13 changes: 6 additions & 7 deletions src/mb_enhanced_cover_art_uploads/providers/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,15 +102,14 @@ export abstract class CoverArtProvider {
}

protected async fetchPage(url: URL, options?: GMXHROptions): Promise<string> {
let resp: Awaited<ReturnType<typeof gmxhr>>;
try {
resp = await gmxhr(url, options);
} catch (err) {
LOGGER.debug(`Received error when fetching ${this.name} page: ${err}`);
const resp = await gmxhr(url, {
// Standardise error messages for 404 pages, otherwise the HTTP error
// will be shown in the UI.
throw new Error(`${this.name} release does not exist`);
}
httpErrorMessages: {
404: `${this.name} release does not exist`,
},
...options,
});

if (typeof resp.finalUrl === 'undefined') {
LOGGER.warn(`Could not detect if ${url.href} caused a redirect`);
Expand Down
4 changes: 4 additions & 0 deletions src/mb_enhanced_cover_art_uploads/providers/tidal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@ export class TidalProvider extends CoverArtProvider {
headers: {
'x-tidal-token': APP_ID,
},
httpErrorMessages: {
404: 'Tidal release does not exist',
},
});

const metadata = safeParseJSON<AlbumMetadata>(resp.responseText, 'Invalid response from Tidal API');
const albumMetadata = metadata.rows[0]?.modules?.[0]?.album;
assertHasValue(albumMetadata, 'Tidal API returned no album, 404?');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,6 @@ describe('tidal provider', () => {
const extractionFailedCases = [{
desc: 'non-existent release',
url: 'https://listen.tidal.com/album/1',
// FIXME: Tidal provider doesn't use the base `fetchPage` and only throws a generic error.
errorMessage: 'HTTP error 404: Not Found',
}];

// eslint-disable-next-line jest/require-hook
Expand Down

0 comments on commit d1813bb

Please sign in to comment.