Skip to content

Commit

Permalink
update throws to use custom errors
Browse files Browse the repository at this point in the history
  • Loading branch information
esizer committed Sep 27, 2024
1 parent a0f1b46 commit cd1674c
Show file tree
Hide file tree
Showing 13 changed files with 80 additions and 59 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,13 @@ export const ErrorBoundary = () => {
<p data-h2-margin="base(x1, 0) p-tablet(0, 0, x3, 0)">
{error.messages.body}
</p>
{error.response?.statusText && (
{error?.error?.message && (
<p
data-h2-margin="base(x1, 0) p-tablet(0, 0, x3, 0)"
data-h2-font-size="base(caption)"
data-h2-font-style="base(italic)"
>
{error.response.statusText}
{error.error.message}
</p>
)}

Expand Down
7 changes: 2 additions & 5 deletions apps/web/src/components/RequireAuth/RequireAuth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ReactNode, useEffect } from "react";

import { useLogger } from "@gc-digital-talent/logger";
import { Loading } from "@gc-digital-talent/ui";
import { notEmpty } from "@gc-digital-talent/helpers";
import { notEmpty, UnauthorizedError } from "@gc-digital-talent/helpers";
import {
RoleName,
useAuthentication,
Expand Down Expand Up @@ -81,10 +81,7 @@ const RequireAuth = ({
pathname: location.pathname,
}),
);
throw new Response("", {
status: 401,
statusText: "Unauthorized",
});
throw new UnauthorizedError();
}

// Note: Need to return a ReactElement
Expand Down
11 changes: 6 additions & 5 deletions apps/web/src/components/Router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Locales, useLocale } from "@gc-digital-talent/i18n";
import { POST_LOGOUT_OVERRIDE_PATH_KEY } from "@gc-digital-talent/auth";
import { Loading } from "@gc-digital-talent/ui";
import { defaultLogger } from "@gc-digital-talent/logger";
import { NotFoundError } from "@gc-digital-talent/helpers";

const createRoute = (locale: Locales) =>
createBrowserRouter([
Expand Down Expand Up @@ -35,7 +36,7 @@ const createRoute = (locale: Locales) =>
{
path: "dashboard",
loader: async () => {
throw new Response("Not Found", { status: 404 }); // unfinished page
throw new NotFoundError();
},
lazy: () =>
import(
Expand Down Expand Up @@ -481,15 +482,15 @@ const createRoute = (locale: Locales) =>
{
path: "*",
loader: () => {
throw new Response("Not Found", { status: 404 });
throw new NotFoundError();
},
},
],
},
{
path: "*",
loader: () => {
throw new Response("Not Found", { status: 404 });
throw new NotFoundError();
},
},
],
Expand Down Expand Up @@ -845,7 +846,7 @@ const createRoute = (locale: Locales) =>
{
path: "*",
loader: () => {
throw new Response("Not Found", { status: 404 });
throw new NotFoundError();
},
},
],
Expand All @@ -868,7 +869,7 @@ const createRoute = (locale: Locales) =>
{
path: "*",
loader: () => {
throw new Response("Not Found", { status: 404 });
throw new NotFoundError();
},
},
],
Expand Down
45 changes: 30 additions & 15 deletions apps/web/src/hooks/useErrorMessages.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import { ReactNode } from "react";
import { defineMessages, useIntl } from "react-intl";
import { useRouteError } from "react-router-dom";
import {
ErrorResponse,
isRouteErrorResponse,
useRouteError,
} from "react-router-dom";

import { errorMessages } from "@gc-digital-talent/i18n";

interface ErrorMessage {
title: ReactNode;
body: ReactNode;
}
interface ErrorResponse {
response: Response;

interface ErrorWithMessages {
error: Error;
messages: ErrorMessage;
}

Expand Down Expand Up @@ -39,33 +44,43 @@ export const routeErrorMessages = defineMessages({
},
});

const useErrorMessages = (): ErrorResponse => {
const error = useRouteError() as Response;
const errorStatusMap: Record<string, number> = {
UnauthorizedError: 401,
NotFoundError: 404,
};

const useErrorMessages = (): ErrorWithMessages => {
const error = useRouteError() as Error | ErrorResponse;
const intl = useIntl();
const messages: Record<number, Omit<ErrorMessage, "error">> = {
401: {
const knownErrorMessages: Record<number, Omit<ErrorMessage, "error">> = {
[401]: {
title: intl.formatMessage(routeErrorMessages.unauthorizedTitle),
body: intl.formatMessage(routeErrorMessages.unauthorizedBody),
},
404: {
[404]: {
title: intl.formatMessage(routeErrorMessages.notFoundTitle),
body: intl.formatMessage(routeErrorMessages.notFoundBody),
},
};

if (error && "status" in error) {
if (error.status in messages) {
if (isRouteErrorResponse(error) && "status" in error) {
return {
error: new Error(error.data?.message),
messages: knownErrorMessages[error.status],
};
}

if (error && "name" in error) {
if (error.name in errorStatusMap) {
return {
response: error,
messages: {
...messages[error.status],
},
error,
messages: knownErrorMessages[errorStatusMap[error.name]],
};
}
}

return {
response: error,
error: new Error(),
messages: {
title: intl.formatMessage(errorMessages.unknownErrorRequestErrorTitle),
body: intl.formatMessage(errorMessages.unknownErrorRequestErrorBody),
Expand Down
7 changes: 2 additions & 5 deletions apps/web/src/hooks/useRequiredParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
defaultLogger,
type Logger,
} from "@gc-digital-talent/logger";
import { notEmpty } from "@gc-digital-talent/helpers";
import { notEmpty, NotFoundError } from "@gc-digital-talent/helpers";
import { commonMessages } from "@gc-digital-talent/i18n";

import invariant from "~/utils/invariant";
Expand Down Expand Up @@ -83,10 +83,7 @@ const useRequiredParams = <
} catch (_err) {
const errorMessage =
message ?? intl.formatMessage(commonMessages.notFound);
throw new Response(errorMessage, {
status: 404,
statusText: errorMessage,
});
throw new NotFoundError(errorMessage);
}

return newParams;
Expand Down
15 changes: 8 additions & 7 deletions apps/web/src/pages/Applications/ApplicationLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@ import { OperationContext, useQuery } from "urql";
import { useEffect } from "react";

import { TableOfContents, Stepper, Loading } from "@gc-digital-talent/ui";
import { empty, isUuidError, notEmpty } from "@gc-digital-talent/helpers";
import { commonMessages, navigationMessages } from "@gc-digital-talent/i18n";
import {
empty,
isUuidError,
notEmpty,
NotFoundError,
} from "@gc-digital-talent/helpers";
import { navigationMessages } from "@gc-digital-talent/i18n";
import { FragmentType, getFragment, graphql } from "@gc-digital-talent/graphql";
import { ROLE_NAME } from "@gc-digital-talent/auth";

Expand Down Expand Up @@ -190,7 +195,6 @@ const Application_Query = graphql(/* GraphQL */ `

const Layout = () => {
const id = useApplicationId();
const intl = useIntl();
const [{ data, fetching, error, stale }] = useQuery({
query: Application_Query,
context,
Expand All @@ -201,10 +205,7 @@ const Layout = () => {

if (error) {
if (isUuidError(error)) {
throw new Response("", {
status: 404,
statusText: intl.formatMessage(commonMessages.notFound),
});
throw new NotFoundError();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
graphql,
Scalars,
} from "@gc-digital-talent/graphql";
import { NotFoundError } from "@gc-digital-talent/helpers";

import useRoutes from "~/hooks/useRoutes";
import useRequiredParams from "~/hooks/useRequiredParams";
Expand Down Expand Up @@ -173,10 +174,7 @@ export const AssessmentPlanBuilderPage = () => {
);

if (!poolId) {
throw new Response(notFoundMessage, {
status: 404,
statusText: "Not Found",
});
throw new NotFoundError(notFoundMessage);
}

const [{ data: queryData, fetching: queryFetching, error: queryError }] =
Expand Down
11 changes: 6 additions & 5 deletions apps/web/src/pages/Pools/EditPoolPage/EditPoolPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ import {
Heading,
} from "@gc-digital-talent/ui";
import { commonMessages } from "@gc-digital-talent/i18n";
import { notEmpty, unpackMaybes } from "@gc-digital-talent/helpers";
import {
notEmpty,
NotFoundError,
unpackMaybes,
} from "@gc-digital-talent/helpers";
import {
graphql,
Scalars,
Expand Down Expand Up @@ -835,10 +839,7 @@ export const EditPoolPage = () => {
);

if (!poolId) {
throw new Response(notFoundMessage, {
status: 404,
statusText: "Not Found",
});
throw new NotFoundError(notFoundMessage);
}

const [{ data, fetching, error }] = useQuery({
Expand Down
1 change: 0 additions & 1 deletion packages/eslint-config-custom/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ module.exports = {
// Temporarily disabled to ease transition to typed linting
"@typescript-eslint/prefer-nullish-coalescing": "off", // Remove in #11376
"@typescript-eslint/require-await": "off", // Remove in #11377
"@typescript-eslint/only-throw-error": "off", // Remove in #11378
"@typescript-eslint/no-misused-promises": "off", // Remove in #11379
"@typescript-eslint/no-base-to-string": "off", // Remove in #11380
"@typescript-eslint/no-floating-promises": "off", // Remove in #11381
Expand Down
13 changes: 13 additions & 0 deletions packages/helpers/src/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export class NotFoundError extends Error {
constructor(message?: string) {
super(message);
this.name = "NotFoundError";
}
}

export class UnauthorizedError extends Error {
constructor(message?: string) {
super(message);
this.name = "UnauthorizedError";
}
}
3 changes: 3 additions & 0 deletions packages/helpers/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
} from "./utils/util";
import useIsSmallScreen from "./hooks/useIsSmallScreen";
import { GraphqlType } from "./types/graphql";
import { NotFoundError, UnauthorizedError } from "./errors";

export {
assertUnreachable,
Expand Down Expand Up @@ -55,5 +56,7 @@ export {
pickMap,
unpackMaybes,
localizedEnumHasValue,
NotFoundError,
UnauthorizedError,
};
export type { GraphqlType };
9 changes: 4 additions & 5 deletions packages/ui/src/components/NotFound/ThrowNotFound.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import { useIntl } from "react-intl";

import { commonMessages } from "@gc-digital-talent/i18n";
import { NotFoundError } from "@gc-digital-talent/helpers";

interface ThrowNotFoundProps {
message?: string;
}

const ThrowNotFound = ({ message }: ThrowNotFoundProps) => {
const intl = useIntl();

throw new Response("", {
status: 404,
statusText: message || intl.formatMessage(commonMessages.notFound),
});
throw new NotFoundError(
message ?? intl.formatMessage(commonMessages.notFound),
);
};

export default ThrowNotFound;
7 changes: 2 additions & 5 deletions packages/ui/src/components/Pending/Pending.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { CombinedError } from "urql";
import { ReactNode, Suspense } from "react";

import { commonMessages } from "@gc-digital-talent/i18n";
import { isUuidError } from "@gc-digital-talent/helpers";
import { isUuidError, NotFoundError } from "@gc-digital-talent/helpers";

import Loading, { LoadingProps } from "../Loading";
import ErrorMessage from "./ErrorMessage";
Expand Down Expand Up @@ -34,10 +34,7 @@ const Pending = ({

if (error) {
if (isUuidError(error)) {
throw new Response("", {
status: 404,
statusText: intl.formatMessage(commonMessages.notFound),
});
throw new NotFoundError(intl.formatMessage(commonMessages.notFound));
}

return <ErrorMessage error={error} />;
Expand Down

0 comments on commit cd1674c

Please sign in to comment.