-
Notifications
You must be signed in to change notification settings - Fork 4
Implement Nimbus error handling components and utilities for consistent user-facing error messages #1613
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Oksamies
wants to merge
1
commit into
12-01-chore_migrate_build_system_to_vite_and_update_ts_config
Choose a base branch
from
11-19-implement_nimbus_error_handling_components_and_utilities_for_consistent_user-facing_error_messages
base: 12-01-chore_migrate_build_system_to_vite_and_update_ts_config
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Implement Nimbus error handling components and utilities for consistent user-facing error messages #1613
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
66 changes: 66 additions & 0 deletions
66
apps/cyberstorm-remix/cyberstorm/utils/__tests__/searchParamsUtils.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import { describe, expect, it, vi } from "vitest"; | ||
|
|
||
| import { | ||
| parseIntegerSearchParam, | ||
| setParamsBlobValue, | ||
| } from "../searchParamsUtils"; | ||
|
|
||
| describe("setParamsBlobValue", () => { | ||
| it("returns a function that updates the blob with the new value", () => { | ||
| const setter = vi.fn(); | ||
| const oldBlob = { foo: "bar", baz: 1 }; | ||
| const key = "foo"; | ||
|
|
||
| const updateFoo = setParamsBlobValue(setter, oldBlob, key); | ||
| updateFoo("qux"); | ||
|
|
||
| expect(setter).toHaveBeenCalledWith({ foo: "qux", baz: 1 }); | ||
| }); | ||
|
|
||
| it("adds a new key if it did not exist", () => { | ||
| const setter = vi.fn(); | ||
| const oldBlob: { foo: string; baz?: number } = { foo: "bar" }; | ||
| const key = "baz"; | ||
|
|
||
| const updateBaz = setParamsBlobValue(setter, oldBlob, key); | ||
| updateBaz(2); | ||
|
|
||
| expect(setter).toHaveBeenCalledWith({ foo: "bar", baz: 2 }); | ||
| }); | ||
| }); | ||
|
|
||
| describe("parseIntegerSearchParam", () => { | ||
| it("returns undefined for null", () => { | ||
| expect(parseIntegerSearchParam(null)).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("returns undefined for empty string", () => { | ||
| expect(parseIntegerSearchParam("")).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("returns undefined for whitespace string", () => { | ||
| expect(parseIntegerSearchParam(" ")).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("returns undefined for non-numeric string", () => { | ||
| expect(parseIntegerSearchParam("abc")).toBeUndefined(); | ||
| expect(parseIntegerSearchParam("123a")).toBeUndefined(); | ||
| expect(parseIntegerSearchParam("a123")).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("returns undefined for float string", () => { | ||
| expect(parseIntegerSearchParam("12.34")).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("returns integer for valid integer string", () => { | ||
| expect(parseIntegerSearchParam("123")).toBe(123); | ||
| expect(parseIntegerSearchParam("0")).toBe(0); | ||
| expect(parseIntegerSearchParam(" 456 ")).toBe(456); | ||
| }); | ||
|
|
||
| it("returns undefined for unsafe integers", () => { | ||
| // Number.MAX_SAFE_INTEGER is 9007199254740991 | ||
| const unsafe = "9007199254740992"; | ||
| expect(parseIntegerSearchParam(unsafe)).toBeUndefined(); | ||
| }); | ||
| }); |
45 changes: 45 additions & 0 deletions
45
apps/cyberstorm-remix/cyberstorm/utils/errors/NimbusErrorBoundary/NimbusErrorBoundary.css
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| @layer nimbus-components { | ||
| .nimbus-error-boundary { | ||
| display: flex; | ||
| flex-direction: column; | ||
| gap: var(--gap-sm); | ||
| align-items: flex-start; | ||
| padding: var(--space-20); | ||
| border: 1px solid rgb(61 78 159 / 0.35); | ||
| border-radius: var(--radius-lg); | ||
| background: linear-gradient( | ||
| 135deg, | ||
| rgb(29 41 95 / 0.35), | ||
| rgb(19 26 68 / 0.5) | ||
| ); | ||
| transition: | ||
| background 180ms ease, | ||
| border-color 180ms ease, | ||
| box-shadow 180ms ease; | ||
| } | ||
|
|
||
| .nimbus-error-boundary:hover { | ||
| border-color: rgb(103 140 255 / 0.55); | ||
| background: linear-gradient( | ||
| 135deg, | ||
| rgb(40 58 132 / 0.45), | ||
| rgb(24 32 86 / 0.65) | ||
| ); | ||
| box-shadow: 0 0.5rem 1.25rem rgb(29 36 82 / 0.45); | ||
| } | ||
|
|
||
| .nimbus-error-boundary__actions { | ||
| display: flex; | ||
| gap: var(--gap-xs); | ||
| align-self: stretch; | ||
| } | ||
|
|
||
| .nimbus-error-boundary__button { | ||
| flex-grow: 1; | ||
| } | ||
|
|
||
| .nimbus-error-boundary__description { | ||
| color: var(--color-text-secondary); | ||
| line-height: var(--line-height-md); | ||
| } | ||
| } |
176 changes: 176 additions & 0 deletions
176
apps/cyberstorm-remix/cyberstorm/utils/errors/NimbusErrorBoundary/NimbusErrorBoundary.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,176 @@ | ||
| import { Component, type ErrorInfo, type ReactNode, useCallback } from "react"; | ||
| import { useAsyncError, useLocation, useRouteError } from "react-router"; | ||
|
|
||
| import { NewButton } from "@thunderstore/cyberstorm"; | ||
| import { classnames } from "@thunderstore/cyberstorm"; | ||
|
|
||
| import { | ||
| resolveRouteErrorPayload, | ||
| safeResolveRouteErrorPayload, | ||
| } from "../resolveRouteErrorPayload"; | ||
| import "./NimbusErrorBoundary.css"; | ||
|
|
||
| interface NimbusErrorBoundaryState { | ||
| error: Error | null; | ||
| } | ||
|
|
||
| export interface NimbusErrorRetryHandlerArgs { | ||
| error: unknown; | ||
| reset: () => void; | ||
| } | ||
|
|
||
| export interface NimbusErrorBoundaryProps { | ||
| children: ReactNode; | ||
| title?: string; | ||
| description?: string; | ||
| retryLabel?: string; | ||
| onError?: (error: Error, info: ErrorInfo) => void; | ||
| onReset?: () => void; | ||
| fallback?: React.ComponentType<NimbusErrorBoundaryFallbackProps>; | ||
| onRetry?: (args: NimbusErrorRetryHandlerArgs) => void; | ||
| fallbackClassName?: string; | ||
| } | ||
|
|
||
| export interface NimbusErrorBoundaryFallbackProps { | ||
| error: unknown; | ||
| reset?: () => void; | ||
| title?: string; | ||
| description?: string; | ||
| retryLabel?: string; | ||
| onRetry?: (args: NimbusErrorRetryHandlerArgs) => void; | ||
| className?: string; | ||
| } | ||
|
|
||
| export type NimbusAwaitErrorElementProps = Pick< | ||
| NimbusErrorBoundaryFallbackProps, | ||
| "title" | "description" | "retryLabel" | "className" | "onRetry" | ||
| >; | ||
|
|
||
| /** | ||
| * NimbusErrorBoundary isolates rendering failures within a subtree and surfaces | ||
| * a consistent recovery UI with an optional "Retry" affordance. | ||
| */ | ||
| export class NimbusErrorBoundary extends Component< | ||
| NimbusErrorBoundaryProps, | ||
| NimbusErrorBoundaryState | ||
| > { | ||
| public state: NimbusErrorBoundaryState = { | ||
| error: null, | ||
| }; | ||
|
|
||
| public static getDerivedStateFromError( | ||
| error: Error | ||
| ): NimbusErrorBoundaryState { | ||
| return { error }; | ||
| } | ||
|
|
||
| public componentDidCatch(error: Error, info: ErrorInfo) { | ||
| this.props.onError?.(error, info); | ||
| } | ||
|
|
||
| private readonly resetBoundary = () => { | ||
| this.setState({ error: null }, () => { | ||
| this.props.onReset?.(); | ||
| }); | ||
| }; | ||
|
|
||
| public override render() { | ||
| const { error } = this.state; | ||
|
|
||
| if (error) { | ||
| const FallbackComponent = | ||
| this.props.fallback ?? NimbusErrorBoundaryFallback; | ||
|
|
||
| return ( | ||
| <FallbackComponent | ||
| error={error} | ||
| reset={this.resetBoundary} | ||
| title={this.props.title} | ||
| description={this.props.description} | ||
| retryLabel={this.props.retryLabel} | ||
| className={this.props.fallbackClassName} | ||
| onRetry={this.props.onRetry} | ||
| /> | ||
| ); | ||
| } | ||
|
|
||
| return this.props.children; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Default fallback surface displayed by {@link NimbusErrorBoundary}. It derives | ||
| * user-facing messaging from the captured error when possible and offers a | ||
| * retry button that either resets the boundary or runs a custom handler. | ||
| */ | ||
| export function NimbusErrorBoundaryFallback( | ||
| props: NimbusErrorBoundaryFallbackProps | ||
| ) { | ||
| const { error, reset, onRetry, className } = props; | ||
| const { pathname, search, hash } = useLocation(); | ||
|
|
||
| const payload = safeResolveRouteErrorPayload(error); | ||
| const title = props.title ?? payload?.headline ?? "Something went wrong"; | ||
| const description = | ||
| props.description ?? payload?.description ?? "Please try again."; | ||
| const retryLabel = props.retryLabel ?? "Retry"; | ||
| const currentLocation = `${pathname}${search}${hash}`; | ||
| const rootClassName = classnames( | ||
| "container container--y container--full nimbus-error-boundary", | ||
| className | ||
| ); | ||
|
|
||
| const noopReset = useCallback(() => {}, []); | ||
| const safeReset = reset ?? noopReset; | ||
|
|
||
| const handleRetry = useCallback(() => { | ||
| if (onRetry) { | ||
| onRetry({ error, reset: safeReset }); | ||
| return; | ||
| } | ||
|
|
||
| window.location.assign(currentLocation); | ||
| }, [currentLocation, error, onRetry, safeReset]); | ||
|
|
||
| return ( | ||
| <div className={rootClassName}> | ||
| <p>{title}</p> | ||
| {description ? ( | ||
| <p className="nimbus-error-boundary__description">{description}</p> | ||
| ) : null} | ||
| <div className="nimbus-error-boundary__actions"> | ||
| <NewButton | ||
| csVariant="accent" | ||
| onClick={handleRetry} | ||
| csSize="medium" | ||
| rootClasses="nimbus-error-boundary__button" | ||
| > | ||
| {retryLabel} | ||
| </NewButton> | ||
| </div> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Generic Await error element that mirrors {@link NimbusErrorBoundaryFallback} | ||
| * behaviour by surfacing the async error alongside Nimbus styling. | ||
| */ | ||
| export function NimbusAwaitErrorElement(props: NimbusAwaitErrorElementProps) { | ||
| const error = useAsyncError(); | ||
|
|
||
| return <NimbusErrorBoundaryFallback {...props} error={error} />; | ||
| } | ||
|
|
||
| export function NimbusDefaultRouteErrorBoundary() { | ||
| const error = useRouteError(); | ||
| const payload = resolveRouteErrorPayload(error); | ||
|
|
||
| return ( | ||
| <NimbusErrorBoundaryFallback | ||
| error={error} | ||
| title={payload.headline} | ||
| description={payload.description} | ||
| /> | ||
| ); | ||
| } |
1 change: 1 addition & 0 deletions
1
apps/cyberstorm-remix/cyberstorm/utils/errors/NimbusErrorBoundary/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export * from "./NimbusErrorBoundary"; |
80 changes: 80 additions & 0 deletions
80
apps/cyberstorm-remix/cyberstorm/utils/errors/handleLoaderError.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import { | ||
| ApiError, | ||
| type UserFacingErrorCategory, | ||
| mapApiErrorToUserFacingError, | ||
| } from "@thunderstore/thunderstore-api"; | ||
|
|
||
| import { defaultErrorMappings } from "./loaderMappings"; | ||
| import { | ||
| type CreateUserFacingErrorResponseOptions, | ||
| type UserFacingErrorPayload, | ||
| throwUserFacingErrorResponse, | ||
| throwUserFacingPayloadResponse, | ||
| } from "./userFacingErrorResponse"; | ||
|
|
||
| export interface LoaderErrorMapping { | ||
| status: number; | ||
| headline: string; | ||
| description?: string; | ||
| category?: UserFacingErrorCategory; | ||
| includeContext?: boolean; | ||
| statusOverride?: number; | ||
| } | ||
|
|
||
| export interface HandleLoaderErrorOptions | ||
| extends CreateUserFacingErrorResponseOptions { | ||
| mappings?: LoaderErrorMapping[]; | ||
| } | ||
|
|
||
| /** | ||
| * Normalises unknown loader errors, promoting mapped API errors to user-facing payloads | ||
| * and rethrowing everything else via `throwUserFacingErrorResponse`. | ||
| */ | ||
| export function handleLoaderError( | ||
anttimaki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| error: unknown, | ||
| options?: HandleLoaderErrorOptions | ||
| ): never { | ||
| if (error instanceof Response) { | ||
| throw error; | ||
| } | ||
|
|
||
| const resolvedOptions: HandleLoaderErrorOptions = options ?? {}; | ||
| const allOptions = defaultErrorMappings.concat( | ||
| resolvedOptions.mappings ?? [] | ||
| ); | ||
|
|
||
| if (error instanceof ApiError && allOptions.length) { | ||
| const mapping = allOptions.findLast((candidate) => { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Now that status is just number and not an array, I think this cleans up to: const mapping = allOptions.findLast(
(mapping) => mapping.status === error.response.status
); |
||
| const statuses = Array.isArray(candidate.status) | ||
| ? candidate.status | ||
| : [candidate.status]; | ||
| return statuses.includes(error.response.status); | ||
| }); | ||
|
|
||
| if (mapping) { | ||
| const base = mapApiErrorToUserFacingError( | ||
| error, | ||
| resolvedOptions.mapOptions | ||
| ); | ||
| const payload: UserFacingErrorPayload = { | ||
| headline: mapping.headline, | ||
| description: mapping.description ?? base.description, | ||
| category: mapping.category ?? base.category, | ||
| status: mapping.statusOverride ?? base.status, | ||
| }; | ||
|
|
||
| payload.context = | ||
| base.context && | ||
| (mapping.includeContext ?? resolvedOptions.includeContext ?? false) | ||
| ? base.context | ||
| : undefined; | ||
|
|
||
| throwUserFacingPayloadResponse(payload, { | ||
| statusOverride: | ||
| mapping.statusOverride ?? resolvedOptions.statusOverride, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| throwUserFacingErrorResponse(error, resolvedOptions); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.