FrontEngineer JungBam

next Error handling 본문

next.js

next Error handling

정밤톨 2023. 7. 27. 13:09

 이전 글에서 loading UI에 대해서 설명했는데, loading UI는 React 18버전에서 제공하는 Suspense를 통해서 구현된다고 설명했다. 그렇다면 이 Error UI는 어떻게 동작하는 것인지도 간단하게 설명하고 지나가겠다.

 이 기능 또한 React에서 제공하는 기능을 통해 구현된 것인데 바로 Error Boundary를 활용한 것이다. React 16버전에 추가된 Error Boundary는 컴포넌트의 자식 컴포넌트에서 Error가 발생하면 Error Boundary의 fallback에 제시된 컴포넌트를 Error UI로 제공한다. 즉 next.js에서 해당 경로에 제시된 error.tsx를 layount.tsx의 Error Boundary fallback에 사용하는 것이다.

 아래 코드는 공식문서에서 제공하는 예시 코드인데 코드를 보고 간단하게 설명하겠다.

'use client' // Error components must be Client Components
 
import { useEffect } from 'react'
 
export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  useEffect(() => {
    // Log the error to an error reporting service
    console.error(error)
  }, [error])
 
  return (
    <div>
      <h2>Something went wrong!</h2>
      <button
        onClick={
          // Attempt to recover by trying to re-render the segment
          () => reset()
        }
      >
        Try again
      </button>
    </div>
  )
}

 코드 제일 상단에서 적혀있듯이 해당 컴포넌트는 무조건 CSR로 렌더링해야한다. 그리고 error와 함께 파라미터로 받는 두번째 파라미터는 리렌더링을 하도록 한다. 

 그 외의 내용은 아래 공식문서를 참고하기 바란다~:)

 

File Conventions: error.js | Next.js

Using App Router Features available in /app

nextjs.org

 

반응형

'next.js' 카테고리의 다른 글

next에서 URL 읽기  (0) 2023.08.11
redirect 설정하기  (0) 2023.07.30
next loading UI  (0) 2023.07.27
api Router  (0) 2023.07.27
next로 ISR 구현하기  (0) 2023.07.26
Comments