Skip to content

Commit

Permalink
refactor: created an ErrorCard component
Browse files Browse the repository at this point in the history
  • Loading branch information
ClementDreptin committed Aug 10, 2023
1 parent 6f0a19f commit 05a883b
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 8 deletions.
16 changes: 8 additions & 8 deletions src/app/[locale]/(search)/results/page.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { getTranslator, redirect } from "next-intl/server";
import { Alert, AlertTitle } from "@mui/material";
import DownloadButton from "./components/DownloadButton";
import ResultCard, { type Result } from "./components/ResultCard";
import ResultsGrid from "./components/ResultsGrid";
import ErrorCard from "@/components/ErrorCard";
import { buildResultPreviewUrl } from "@/lib/istexApi";
import useSearchParams from "@/lib/useSearchParams";
import type { GenerateMetadata, Page } from "@/types/next";
Expand All @@ -28,7 +28,11 @@ async function getResults(
// API call
const response = await fetch(url, { cache: "no-store" });
if (!response.ok) {
throw new Error(`API responded with a ${response.status} status code!`);
const error = new Error(
`API responded with a ${response.status} status code!`
);
error.cause = response.status;
throw error;
}

// Fill some missing fields with placeholder texts
Expand Down Expand Up @@ -78,12 +82,8 @@ const ResultsPage: Page = async ({
);
} catch (error) {
return (
error instanceof Error && (
<Alert severity="error">
<AlertTitle>Error</AlertTitle>
{error.message}
</Alert>
)
error instanceof Error &&
typeof error.cause === "number" && <ErrorCard code={error.cause} />
);
}
};
Expand Down
20 changes: 20 additions & 0 deletions src/components/ErrorCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { useTranslations } from "next-intl";
import { Alert, AlertTitle } from "@mui/material";
import type { ServerComponent } from "@/types/next";

interface ErrorCardProps {
code?: number;
}

const ErrorCard: ServerComponent<ErrorCardProps> = ({ code }) => {
const t = useTranslations("ErrorCard");

return (
<Alert severity="error">
<AlertTitle>{t("title")}</AlertTitle>
{t(code?.toString() ?? "default") + (code != null ? ` (${code})` : "")}
</Alert>
);
};

export default ErrorCard;
5 changes: 5 additions & 0 deletions src/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@
"seeMoreLink": "EN SAVOIR PLUS",
"downloadButton": "Télécharger le corpus"
},
"ErrorCard": {
"title": "Erreur",
"400": "Une erreur de syntaxe a été détectée.",
"default": "Une erreur est survenue, veuillez réessayer ultérieurement."
},
"config": {
"usages": {
"custom": {
Expand Down

0 comments on commit 05a883b

Please sign in to comment.