Skip to content
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

에러 바운더리 설정 #10

Merged
merged 2 commits into from
Aug 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/api/_http.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import Axios, { AxiosRequestConfig } from "axios";

interface LawLowResponse<T = unknown> {
export interface LawLowResponse<T = unknown> {
success: boolean;
data?: T;
statusCode?: number;
errorMessage?: string;
errorDetail?: string;
message?: string[];
detail?: string[];
}

class Http {
Expand Down
56 changes: 56 additions & 0 deletions src/components/ErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react/destructuring-assignment */
import { Component, ReactNode } from "react";

import { AxiosError } from "axios";

import {
CustomError,
ErrorBoundaryProps,
ErrorBoundaryState,
} from "@/interface/error";

interface Props extends ErrorBoundaryProps {
children: ReactNode;
}
class ErrorBoundary extends Component<Props, ErrorBoundaryState> {
constructor(props: Props) {
super(props);
this.state = {
error: null,
};
this.resetErrorBoundary = this.resetErrorBoundary.bind(this);
}

static getDerivedStateFromError(error: Error | AxiosError) {
return { error, shouldRethrow: false, shouldShowFallbackUI: true };
}

resetErrorBoundary() {
this.setState({
error: null,
});
}

render() {
const { fallbackComponent: FallbackComponent, children } = this.props;
const { error } = this.state;

if (error) {
return (
<FallbackComponent
error={
error !== null && !("name" in error)
? ({ name: "Error" } as CustomError)
: error
}
resetErrorBoundary={this.resetErrorBoundary}
/>
);
}

return children;
}
}

export default ErrorBoundary;
73 changes: 73 additions & 0 deletions src/components/ErrorFallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { useCallback, useState } from "react";

import { Button, Typography } from "@mui/material";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";

import { ErrorFallbackProps } from "@/interface/error";

const ContentWrapper = styled.main`
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 3rem;

.msg {
font-family: SUIT;
font-size: 20px;
font-weight: 500;
}

.MuiButton-root {
height: 40px;
width: 60vw;
border-radius: 15.867px;
background: var(--orange, #ffbc10);
color: var(--black-2, #3a3a3a);
font-family: SUIT;
font-size: 14.733px;
font-style: normal;
font-weight: 700;
line-height: 150%; /* 22.1px */
letter-spacing: -0.227px;
}
`;

const ERROR_MAP: { [key: string]: string } = {
"q should not be empty": "검색어는 비어 있으면 안돼요.😢",
};

const ErrorFallback = ({ error, resetErrorBoundary }: ErrorFallbackProps) => {
const [msg] = useState(() => {
if (error.name === "AxiosError") {
// eslint-disable-next-line no-unsafe-optional-chaining
const m = error.response?.data.message ?? ([] as string[]);
const mArr = m
.map((x) =>
x in ERROR_MAP ? ERROR_MAP[x as keyof typeof ERROR_MAP] : [],
)
.flat();
if (mArr.length > 0) return mArr;
}
return ["원인 모를 에러가 발생했어요.😢"];
});

const navigate = useNavigate();

const handleClickGoHome = useCallback(() => {
navigate("/");
resetErrorBoundary();
}, []);

return (
<ContentWrapper>
<Typography className="msg">{msg}</Typography>
<Button onClick={handleClickGoHome}>홈으로 이동하기</Button>
</ContentWrapper>
);
};

export default ErrorFallback;
35 changes: 35 additions & 0 deletions src/interface/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { ComponentType } from "react";

import { AxiosError } from "axios";

import { LawLowResponse } from "@/api/_http";

export interface CommonErrorProps {
statusCode: Pick<LawLowResponse, "statusCode">["statusCode"];
message: Pick<LawLowResponse, "message">["message"];
onReset?: () => void;
}

export interface CustomError extends Error {
name: "Error";
}

export type ErrorBoundaryState =
| {
error: null;
}
| {
error: CustomError;
}
| {
error: AxiosError<LawLowResponse>;
};

export interface ErrorFallbackProps {
error: CustomError | AxiosError<LawLowResponse>;
resetErrorBoundary: () => void;
}

export interface ErrorBoundaryProps {
fallbackComponent: ComponentType<ErrorFallbackProps>;
}
51 changes: 51 additions & 0 deletions src/pages/NotFound/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { useCallback } from "react";

import { Box, Button } from "@mui/material";
import { useNavigate } from "react-router";
import styled from "styled-components";

const ContentWrapper = styled.main`
position: absolute;
top: 56px;
width: 100%;
height: calc(100% - 56px);
display: flex;
flex-direction: column;
gap: 3rem;
justify-content: center;
align-items: center;
font-family: SUIT;
font-size: 20px;
font-weight: 500;

.MuiButton-root {
height: 40px;
width: 60%;
border-radius: 15.867px;
background: var(--orange, #ffbc10);
color: var(--black-2, #3a3a3a);
font-family: SUIT;
font-size: 14.733px;
font-style: normal;
font-weight: 700;
line-height: 150%; /* 22.1px */
letter-spacing: -0.227px;
}
`;

const NotFound = () => {
const navigate = useNavigate();

const handleClickGoHome = useCallback(() => {
navigate("/", { replace: true });
}, []);

return (
<ContentWrapper>
<Box>🚧404🚧 존재하지 않는 페이지에요😢</Box>
<Button onClick={handleClickGoHome}>홈으로 돌아가기</Button>
</ContentWrapper>
);
};

export default NotFound;
41 changes: 25 additions & 16 deletions src/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,35 @@
/* eslint-disable react/no-unstable-nested-components */
import { Suspense } from "react";

import {
// useQueryErrorResetBoundary,
QueryErrorResetBoundary,
} from "@tanstack/react-query";
import { createBrowserRouter } from "react-router-dom";
import { styled } from "styled-components";

import AppRoutes from "./AppRoutes";
import ErrorBoundary from "@/components/ErrorBoundary";
import ErrorFallback from "@/components/ErrorFallback";

const TodoContainer = styled.section`
display: flex;
height: 100%;
width: 100%;
justify-content: center;
align-items: center;
font-size: 50px;
font-weight: 500;
`;
import AppRoutes from "./AppRoutes";

const TodoPage = () => {
return <TodoContainer>⚙️작업중⚙️</TodoContainer>;
const ErrorLayer = () => {
return (
<Suspense>
<QueryErrorResetBoundary>
{() => (
<ErrorBoundary fallbackComponent={ErrorFallback}>
<AppRoutes />
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
</Suspense>
);
};

const router = createBrowserRouter([
{
path: "/",
element: <AppRoutes />,
element: <ErrorLayer />,
children: [
{
path: "",
Expand Down Expand Up @@ -68,8 +77,8 @@ const router = createBrowserRouter([
{
path: "*",
async lazy() {
const NotFound = await TodoPage;
return { Component: NotFound };
const NotFound = await import("@pages/NotFound");
return { Component: NotFound.default };
},
},
],
Expand Down