Skip to content

Commit

Permalink
add APIException
Browse files Browse the repository at this point in the history
  • Loading branch information
evansloan committed Mar 5, 2024
1 parent f567222 commit b752f3f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
19 changes: 11 additions & 8 deletions app/log/[username]/[[...page]]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import { CollectionLog } from '@/components/collection-log';
import Item from '@/components/item';
import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { CollectionLogAPI } from '@/lib/api/collection-log/collection-log-api';
import {
APIException,
CollectionLogAPI,
} from '@/lib/api/collection-log/collection-log-api';
import { getFullCollectionLog } from '@/lib/collection-log-helpers';

interface PageProps {
Expand All @@ -30,7 +33,11 @@ const fetchCollectionLogData = async (username: string) => {
recentItems: await CollectionLogAPI.getRecentItems(username),
};
} catch (e) {
return notFound();
if (e instanceof APIException && e.code === 404) {
return notFound();
}

throw e;
}
};

Expand All @@ -40,12 +47,8 @@ const Page = async ({ params: { username, page } }: PageProps) => {
page = decodeURI(page);
}

const {
collectionLog,
ranks,
recentItems,
settings,
} = await fetchCollectionLogData(username);
const { collectionLog, ranks, recentItems, settings } =
await fetchCollectionLogData(username);

return (
<main className='flex flex-col items-center justify-between'>
Expand Down
20 changes: 16 additions & 4 deletions lib/api/collection-log/collection-log-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@ import {
UserSettingsResponse,
} from './responses';

class APIException extends Error {
constructor(
public code: number,
message: string,
options?: ErrorOptions
) {
super(message, options);
}
}

class CollectionLogAPI {
private static readonly BASE_URL = 'https://api.collectionlog.net';
private static readonly COLLECTION_LOG_ENDPOINT = 'collectionlog';
Expand Down Expand Up @@ -58,9 +68,11 @@ class CollectionLogAPI {
const response = await fetch(url, config);
if (!response.ok) {
const error = (await response.json()) as BaseResponse;
throw new Error(`${response.status}: ${error.error}`, {
cause: response.url,
});
throw new APIException(
response.status,
`${response.status}: ${error.error}`,
{ cause: response.url }
);
}

return await response.json();
Expand Down Expand Up @@ -341,4 +353,4 @@ class CollectionLogAPI {
};
}

export { CollectionLogAPI };
export { APIException, CollectionLogAPI };

0 comments on commit b752f3f

Please sign in to comment.