Skip to content

Commit

Permalink
fix: enhance error messages when Fetch API fails (#893)
Browse files Browse the repository at this point in the history
  • Loading branch information
gauthier-th authored Jul 26, 2024
1 parent 3fc14c9 commit fccfca6
Show file tree
Hide file tree
Showing 16 changed files with 308 additions and 59 deletions.
62 changes: 56 additions & 6 deletions server/api/externalapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ class ExternalAPI {
if (!response.ok) {
const text = await response.text();
throw new Error(
`${response.status} ${response.statusText}${text ? ': ' + text : ''}`
`${response.status} ${response.statusText}${text ? ': ' + text : ''}`,
{
cause: response,
}
);
}
const data = await this.getDataFromResponse(response);
Expand Down Expand Up @@ -106,6 +109,15 @@ class ExternalAPI {
},
body: JSON.stringify(data),
});
if (!response.ok) {
const text = await response.text();
throw new Error(
`${response.status} ${response.statusText}${text ? ': ' + text : ''}`,
{
cause: response,
}
);
}
const resData = await this.getDataFromResponse(response);

if (this.cache) {
Expand Down Expand Up @@ -141,6 +153,15 @@ class ExternalAPI {
},
body: JSON.stringify(data),
});
if (!response.ok) {
const text = await response.text();
throw new Error(
`${response.status} ${response.statusText}${text ? ': ' + text : ''}`,
{
cause: response,
}
);
}
const resData = await this.getDataFromResponse(response);

if (this.cache) {
Expand All @@ -163,6 +184,15 @@ class ExternalAPI {
...config?.headers,
},
});
if (!response.ok) {
const text = await response.text();
throw new Error(
`${response.status} ${response.statusText}${text ? ': ' + text : ''}`,
{
cause: response,
}
);
}
const data = await this.getDataFromResponse(response);

return data;
Expand Down Expand Up @@ -197,6 +227,17 @@ class ExternalAPI {
...config?.headers,
},
}).then(async (response) => {
if (!response.ok) {
const text = await response.text();
throw new Error(
`${response.status} ${response.statusText}${
text ? ': ' + text : ''
}`,
{
cause: response,
}
);
}
const data = await this.getDataFromResponse(response);
this.cache?.set(cacheKey, data, ttl ?? DEFAULT_TTL);
});
Expand All @@ -212,6 +253,15 @@ class ExternalAPI {
...config?.headers,
},
});
if (!response.ok) {
const text = await response.text();
throw new Error(
`${response.status} ${response.statusText}${text ? ': ' + text : ''}`,
{
cause: response,
}
);
}
const data = await this.getDataFromResponse(response);

if (this.cache) {
Expand Down Expand Up @@ -250,13 +300,13 @@ class ExternalAPI {
}

private async getDataFromResponse(response: Response) {
const contentType = response.headers.get('Content-Type')?.split(';')[0];
if (contentType === 'application/json') {
const contentType = response.headers.get('Content-Type');
if (contentType?.includes('application/json')) {
return await response.json();
} else if (
contentType === 'application/xml' ||
contentType === 'text/html' ||
contentType === 'text/plain'
contentType?.includes('application/xml') ||
contentType?.includes('text/html') ||
contentType?.includes('text/plain')
) {
return await response.text();
} else {
Expand Down
22 changes: 11 additions & 11 deletions server/api/jellyfin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ class JellyfinAPI extends ExternalAPI {
try {
return await authenticate(false);
} catch (e) {
const status = e.response?.status;
const status = e.cause?.status;

const networkErrorCodes = new Set([
'ECONNREFUSED',
Expand Down Expand Up @@ -190,7 +190,7 @@ class JellyfinAPI extends ExternalAPI {

return systemInfoResponse;
} catch (e) {
throw new ApiError(e.response?.status, ApiErrorCode.InvalidAuthToken);
throw new ApiError(e.cause?.status, ApiErrorCode.InvalidAuthToken);
}
}

Expand All @@ -207,7 +207,7 @@ class JellyfinAPI extends ExternalAPI {
{ label: 'Jellyfin API' }
);

throw new ApiError(e.response?.status, ApiErrorCode.Unknown);
throw new ApiError(e.cause?.status, ApiErrorCode.Unknown);
}
}

Expand All @@ -222,7 +222,7 @@ class JellyfinAPI extends ExternalAPI {
{ label: 'Jellyfin API' }
);

throw new ApiError(e.response?.status, ApiErrorCode.InvalidAuthToken);
throw new ApiError(e.cause?.status, ApiErrorCode.InvalidAuthToken);
}
}

Expand All @@ -238,7 +238,7 @@ class JellyfinAPI extends ExternalAPI {
{ label: 'Jellyfin API' }
);

throw new ApiError(e.response?.status, ApiErrorCode.InvalidAuthToken);
throw new ApiError(e.cause?.status, ApiErrorCode.InvalidAuthToken);
}
}

Expand Down Expand Up @@ -317,7 +317,7 @@ class JellyfinAPI extends ExternalAPI {
{ label: 'Jellyfin API' }
);

throw new ApiError(e.response?.status, ApiErrorCode.InvalidAuthToken);
throw new ApiError(e.cause?.status, ApiErrorCode.InvalidAuthToken);
}
}

Expand All @@ -338,7 +338,7 @@ class JellyfinAPI extends ExternalAPI {
{ label: 'Jellyfin API' }
);

throw new ApiError(e.response?.status, ApiErrorCode.InvalidAuthToken);
throw new ApiError(e.cause?.status, ApiErrorCode.InvalidAuthToken);
}
}

Expand All @@ -353,7 +353,7 @@ class JellyfinAPI extends ExternalAPI {
return itemResponse;
} catch (e) {
if (availabilitySync.running) {
if (e.response && e.response.status === 500) {
if (e.cause?.status === 500) {
return undefined;
}
}
Expand All @@ -362,7 +362,7 @@ class JellyfinAPI extends ExternalAPI {
`Something went wrong while getting library content from the Jellyfin server: ${e.message}`,
{ label: 'Jellyfin API' }
);
throw new ApiError(e.response?.status, ApiErrorCode.InvalidAuthToken);
throw new ApiError(e.cause?.status, ApiErrorCode.InvalidAuthToken);
}
}

Expand All @@ -377,7 +377,7 @@ class JellyfinAPI extends ExternalAPI {
{ label: 'Jellyfin API' }
);

throw new ApiError(e.response?.status, ApiErrorCode.InvalidAuthToken);
throw new ApiError(e.cause?.status, ApiErrorCode.InvalidAuthToken);
}
}

Expand All @@ -402,7 +402,7 @@ class JellyfinAPI extends ExternalAPI {
{ label: 'Jellyfin API' }
);

throw new ApiError(e.response?.status, ApiErrorCode.InvalidAuthToken);
throw new ApiError(e.cause?.status, ApiErrorCode.InvalidAuthToken);
}
}
}
Expand Down
9 changes: 8 additions & 1 deletion server/api/servarr/radarr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,20 @@ class RadarrAPI extends ServarrBase<{ movieId: number }> {
}
return data;
} catch (e) {
let errorData;
try {
errorData = await e.cause?.text();
errorData = JSON.parse(errorData);
} catch {
/* empty */
}
logger.error(
'Failed to add movie to Radarr. This might happen if the movie already exists, in which case you can safely ignore this error.',
{
label: 'Radarr',
errorMessage: e.message,
options,
response: e?.response?.data,
response: errorData,
}
);
throw new Error('Failed to add movie to Radarr');
Expand Down
9 changes: 8 additions & 1 deletion server/api/servarr/sonarr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,11 +257,18 @@ class SonarrAPI extends ServarrBase<{

return createdSeriesData;
} catch (e) {
let errorData;
try {
errorData = await e.cause?.text();
errorData = JSON.parse(errorData);
} catch {
/* empty */
}
logger.error('Something went wrong while adding a series to Sonarr.', {
label: 'Sonarr API',
errorMessage: e.message,
options,
response: e?.response?.data,
response: errorData,
});
throw new Error('Failed to add series');
}
Expand Down
14 changes: 12 additions & 2 deletions server/lib/notifications/agents/discord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ class DiscordAgent
}
}

await fetch(settings.options.webhookUrl, {
const response = await fetch(settings.options.webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand All @@ -305,15 +305,25 @@ class DiscordAgent
content: userMentions.join(' '),
} as DiscordWebhookPayload),
});
if (!response.ok) {
throw new Error(response.statusText, { cause: response });
}

return true;
} catch (e) {
let errorData;
try {
errorData = await e.cause?.text();
errorData = JSON.parse(errorData);
} catch {
/* empty */
}
logger.error('Error sending Discord notification', {
label: 'Notifications',
type: Notification[type],
subject: payload.subject,
errorMessage: e.message,
response: e.response?.data,
response: errorData,
});

return false;
Expand Down
14 changes: 12 additions & 2 deletions server/lib/notifications/agents/gotify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,22 +132,32 @@ class GotifyAgent
const endpoint = `${settings.options.url}/message?token=${settings.options.token}`;
const notificationPayload = this.getNotificationPayload(type, payload);

await fetch(endpoint, {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(notificationPayload),
});
if (!response.ok) {
throw new Error(response.statusText, { cause: response });
}

return true;
} catch (e) {
let errorData;
try {
errorData = await e.cause?.text();
errorData = JSON.parse(errorData);
} catch {
/* empty */
}
logger.error('Error sending Gotify notification', {
label: 'Notifications',
type: Notification[type],
subject: payload.subject,
errorMessage: e.message,
response: e.response?.data,
response: errorData,
});

return false;
Expand Down
14 changes: 12 additions & 2 deletions server/lib/notifications/agents/lunasea.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ class LunaSeaAgent
});

try {
await fetch(settings.options.webhookUrl, {
const response = await fetch(settings.options.webhookUrl, {
method: 'POST',
headers: settings.options.profileName
? {
Expand All @@ -114,15 +114,25 @@ class LunaSeaAgent
},
body: JSON.stringify(this.buildPayload(type, payload)),
});
if (!response.ok) {
throw new Error(response.statusText, { cause: response });
}

return true;
} catch (e) {
let errorData;
try {
errorData = await e.cause?.text();
errorData = JSON.parse(errorData);
} catch {
/* empty */
}
logger.error('Error sending LunaSea notification', {
label: 'Notifications',
type: Notification[type],
subject: payload.subject,
errorMessage: e.message,
response: e.response?.data,
response: errorData,
});

return false;
Expand Down
Loading

0 comments on commit fccfca6

Please sign in to comment.