NextJS - Routing/Error Handling

Hunter Joe·2024년 12월 19일
0

에러는 두 가지로 나뉠 수 있다.
1. Expected Error : 예상 가능 오류
2. Uncaught Exceptions: 예기치 못한 오류

📌Handling Expected Errors

  • 예상된 오류란 애플리케이션의 정상적인 동작 중 발생할 수 있는 오류
  • sever-side form validation(서버 측 폼 유효성 검사 오류)
  • Failed requests(실패한 네트워크 요청)

→ 이러한 오류는 명시적으로 처리해야 하며, 클라이언트에게 반환되어야 한다.

Handling Expected Errors from Server Actions

  • useActionState hook을 사용하여 서버 액션(Server Actions)의 상태를 관리하고 처리 가능 이러한 방식은 try/catch블록을 사용하지 않고 오류를 처리할 수 있도록 도와준다.
  • 예상된 오류는 예외(throw new Error)로 처리하는 것이 아니라, 반환값(return value)으로 모델링 해야한다.
'use server'
 
import { redirect } from 'next/navigation'
 
export async function createUser(prevState: any, formData: FormData) {
  const res = await fetch('https://...')
  const json = await res.json()
 
  if (!res.ok) {
    return { message: 'Please enter a valid email' }
  }
 
  redirect('/dashboard')
}

다음 server action을 useActionState hook에 전달하고, 반환된 state를 사용하여 오류 메세지를 표시할 수 있다.

'use client'
 
import { useActionState } from 'react'
import { createUser } from '@/app/actions'
 
const initialState = {
  message: '',
}
 
export function Signup() {
  const [state, formAction, pending] = useActionState(createUser, initialState)
 
  return (
    <form action={formAction}>
      <label htmlFor="email">Email</label>
      <input type="text" id="email" name="email" required />
      {/* ... */}
      <p aria-live="polite">{state?.message}</p>
      <button disabled={pending}>Sign up</button>
    </form>
  )
}

반환된 state값을 사용해 toast 메세지를 클라이언트 컴포넌트에서 보여줄 수 있다.

Handling Expected Errors from Server Components

서버 컴포넌트 내에서 데이터를 가져올 때 response를 활용해 if 조건부로 오류 메세지를 렌더링하거나 redirect할 수 있다.

export default async function Page() {
  const res = await fetch(`https://...`)
  const data = await res.json()
 
  if (!res.ok) {
    return 'There was an error.'
  }
 
  return '...'
}

📌Uncaught Exceptions

  • 예상되지 않은 오류(애플리케이션의 정상적 흐름에서 벗어나 발생해서는 안 되는 버그 또는 문제)
  • 이러한 오류는 throw new Error를 통해 처리해야되며 error boundaries에서 처리 된다.

1️⃣Common (일반적)

  • error.js를 사용해 root layout 아래에서 오류를 처리한다.

2️⃣Optional(더 세부적인 오류 처리)

  • 각 경로별 error.js파일을 추가해 특정 페이지에서 발생하는 오류를 처리

3️⃣Uncommon(잘 사용되지 않음)

  • 전역 오류 처리는 global-error.js파일에서 관리할 수 있다.

Using Error Boundaries

  • Next.js는 오류 경계(Error Boundaries)를 사용해 예상되지 않은 오류를 처리
  • 오류 경계는 자식 컴포넌트에서 발생한 오류를 감지 애플리케이션이 완전히 충동하는 대신 Fallback UI를 보여준다.
// app/dashboard/error.tsx
'use client' // Error boundaries 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>
  )
}

오류를 상위(부모) 오류 경계(Parent Error Boundary)로 전파하고 싶다면 error컴포넌트에서 throw를 사용해 예외를 발생시키면 된다.

Handling Errors in Nested Routes

  • 오류는 가장 가까운 상위 오류 경계(Parent Error Boundary)로 전파 됨
  • 이를 통해 경로 계층(Route Hierarchy)의 다양한 수준(Level)에 error.tsx 파일을 배치해 세분화된 오류 처리가 가능
profile
Async FE 취업 준비중.. Await .. (취업완료 대기중) ..

0개의 댓글

관련 채용 정보