0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 강의

액션의 오류 처리

사용자에게 안정적인 피드백을 제공할 수 있도록 Server Actions 내부에 효과적인 오류 처리 전략을 구현합니다.

액션의 오류 처리은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack (App Router + Server Actions) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Robust Server Actions

When building applications, things can go wrong! Data might be invalid, a database might be unreachable, or an external API could fail.

Effective error handling in Server Actions is crucial for a smooth user experience and maintaining data integrity. It prevents crashes and provides clear feedback.

The `try-catch` Block

In JavaScript/TypeScript, the fundamental way to handle potential errors is using a try-catch block. It allows you to 'try' executing code and 'catch' any errors that occur.

  • Code inside the try block is executed.
  • If an error occurs, execution jumps to the catch block.
  • The catch block receives the error object, allowing you to handle it gracefully.

Server Action Error Example

Let's look at a simple Server Action that might fail. Imagine an action that divides two numbers, but one could be zero.

Without error handling, a division by zero would crash the action and potentially the client-side form submission.

export async function divideNumbers(formData: FormData) {
  const num1 = Number(formData.get('num1'));
  const num2 = Number(formData.get('num2'));

  if (num2 === 0) {
    throw new Error('Cannot divide by zero!');
  }

  const result = num1 / num2;
  return { success: true, result };
}

Catching Errors on the Server

To prevent the action from crashing, we wrap the risky code in a try-catch block. This allows us to log the error on the server and prevent sensitive error details from reaching the client.

export async function divideNumbers(formData: FormData) {
  try {
    const num1 = Number(formData.get('num1'));
    const num2 = Number(formData.get('num2'));

    if (num2 === 0) {
      throw new Error('Cannot divide by zero!');
    }

    const result = num1 / num2;
    return { success: true, result };
  } catch (error: any) {
    console.error('Action Error:', error.message); // Log on server
    // Do NOT return `error` object directly to client!
    return { success: false, error: 'An unexpected error occurred.' };
  }
}

Returning Client-Friendly Errors

After catching an error on the server, we need to return a meaningful, client-friendly message. This message helps users understand what went wrong without exposing internal server details.

  • Return an object with a success: false flag.
  • Include an error property with a user-friendly message.
  • Avoid sending raw error stack traces to the client for security.

Action with Client Error Return

Here's how our divideNumbers action looks when returning specific error messages to the client:

Notice how different errors get different messages, and a generic message is used for unexpected errors.

export async function divideNumbers(formData: FormData) {
  try {
    const num1 = Number(formData.get('num1'));
    const num2 = Number(formData.get('num2'));

    if (isNaN(num1) || isNaN(num2)) {
      throw new Error('Invalid input: Please enter numbers.');
    }
    if (num2 === 0) {
      throw new Error('Division by zero is not allowed.');
    }

    const result = num1 / num2;
    return { success: true, result };
  } catch (error: any) {
    console.error('Server Action Failed:', error.message);
    return { success: false, error: error.message || 'Unknown error occurred.' };
  }
}

Client-Side Error Display

On the client, after calling a Server Action, you'll receive the returned object. You can then check the success and error properties to update your UI.

This allows you to show an error message to the user, disable parts of the form, or take other corrective actions.

import { useState } from 'react';
import { divideNumbers } from './actions'; // Your Server Action

export default function CalculatorForm() {
  const [message, setMessage] = useState('');

  async function handleSubmit(formData: FormData) {
    const res = await divideNumbers(formData);
    if (res.success) {
      setMessage(`Result: ${res.result}`);
    } else {
      setMessage(`Error: ${res.error}`);
    }
  }

  return (
    <form action={handleSubmit}>
      <input type="number" name="num1" />
      <input type="number" name="num2" />
      <button type="submit">Calculate</button>
      {message && <p>{message}</p>}
    </form>
  );
}

React `useFormState` Hook

For forms, React's useFormState hook is specifically designed to manage state returned by a Server Action. It simplifies displaying feedback (like success or error messages) after a form submission.

It takes your action and an initial state, and returns the current state and an updated action that you pass to your <form>'s action prop.

Using `useFormState` for Errors

Here's how to integrate useFormState to display error messages directly within your form component. It makes handling the action's response very clean.

import { useFormState } from 'react-dom';
import { divideNumbers } from './actions';

const initialState = { success: false, error: '', result: null };

export default function CalculatorForm() {
  const [state, formAction] = useFormState(divideNumbers, initialState);

  return (
    <form action={formAction}>
      <input type="number" name="num1" placeholder="Number 1" />
      <input type="number" name="num2" placeholder="Number 2" />
      <button type="submit">Calculate</button>
      {state.success && <p>Result: {state.result}</p>}
      {!state.success && state.error && <p style={{ color: 'red' }}>{state.error}</p>}
    </form>
  );
}

Handling Server Action Errors

Which of the following is the BEST practice for handling errors caught within a Next.js Server Action?

Recap: Error Handling

You've mastered error handling in Next.js Server Actions!

  • Use try-catch blocks to gracefully handle errors on the server.
  • Log server-side errors for debugging and monitoring.
  • Return client-friendly error messages using a structured object (e.g., { success: false, error: 'message' }).
  • Utilize React's useFormState hook to easily manage and display action results and errors in your forms.

Robust error handling makes your applications more reliable and user-friendly!

자주 묻는 질문

“액션의 오류 처리” 강의는 무료인가요?

네 — “액션의 오류 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 4개의 강의가 포함되어 있습니다.

“액션의 오류 처리”에서 뭘 배우나요?

사용자에게 안정적인 피드백을 제공할 수 있도록 Server Actions 내부에 효과적인 오류 처리 전략을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack (App Router + Server Actions)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Next.js 15 Fullstack (App Router + Server Actions)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack (App Router + Server Actions)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“액션의 오류 처리” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Next.js 15 Fullstack (App Router + Server Actions) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Next.js 15 Fullstack (App Router + Server Actions) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 기본 서버 액션 폼
  2. 데이터 변경 및 재검증
  3. 액션의 오류 처리
  4. Server Actions를 활용한 낙관적 UI와 대기 상태
← Next.js 15 Fullstack (App Router + Server Actions)(으)로 돌아가기