-
componentDidCatch 으로 전역적으로 에러 핸들링 하기.개발/Next.JS 2023. 5. 5. 14:31
React 16버전 부터 나온
componentDidCatch 라는 라이프사이클 이용해
쉽게 에러 핸들링이 가능해졌다.
클래스형 ErrorBoundary 컴포넌트 안에 componentDidCatch 메소드를 선언해주고
루트 컴포넌트에선 Provider처럼 컴포넌트를 감싸주는 형태를 갖추면 된다. 사용법은 아래와같다.
import { Component } from "react"; class ErrorBonudary extends Component { constructor(props) { super(props) this.state = { isError: false, errorMsg: "", } } // 아래에 SomeComponent.tsx에서 발생한 예외를 감지. componentDidCatch(error, errorInfo) { this.setState({ isError: true, errorMsg: error }) } render() { if (this.state.isError === true) { return <h1>Something Wrong!</h1> } return this.props.children; } }
_app.tsx import ErrorBoundary from "./ErrorBoundary"; export default function App({ Component, pageProps}) { return ( <> <ErrorBoundary> <Component/> </ErrorBoundary> </> ) }
// SomeComponent.tsx import { useEffect } from "react"; export default function SomeComponent() { useEffect(() => { throw new Error("Something error"); },[]) return ( <></> ); }
componentDidCatch는 클래스형 컴포넌트에서만 사용 가능한 라이프사이클 메소드이고
루트 컴포넌트에서 컴포넌트를 ErrorBonudary로 감싸게 되면
컴포넌트에서 예외를 발생하게 되면 ErrorBoundary 의 componentDidCatch 에서
try catch 문의 catch 문 처럼 예외를 감지할 수 있다.
react-query 처럼 사이드이펙트를 쉽게 핸들링 할 수 있는 패키지와 같이 활용하면 더욱 좋을것 같다.
'개발 > Next.JS' 카테고리의 다른 글
vercel 으로 배포한 next 앱에서 api 호출 시 308 에러가 났던 이유 (0) 2023.10.09 Redux에서 쓰이는 Flux 패턴이란? (0) 2023.07.30 [react-query] useInfiniteQuery 사용법. (0) 2023.04.19 [react-query] getServerSideProps에서 prefetchQuery 사용법 (0) 2023.04.19 Next.js Context 사용법 (0) 2023.03.21