0Pricing
tRPC End-to-End Type Safe APIs · 강의

사용자 지정 오류 형식

백엔드에서 사용자 지정 오류 형식을 정의하고 발생시켜 프런트엔드에 올바르게 전달합니다.

사용자 지정 오류 형식은(는) CoddyKit의 무료 tRPC End-to-End Type Safe APIs 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 tRPC End-to-End Type Safe APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

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

Why Custom Error Types?

In tRPC, we often use TRPCError for handling issues. But sometimes, you need more specific error types.

  • Clarity: Custom errors make your code clearer about what went wrong.
  • Specific Handling: Allows the frontend to react differently to distinct error conditions.
  • Better Debugging: Provides more context than a generic error.

Let's learn how to define and use them!

Basic Custom Error Class

At its simplest, a custom error is a class that extends JavaScript's built-in Error class. This ensures it behaves like a standard error.

It usually takes a message and sets its own name property.

class MyCustomError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'MyCustomError';
  }
}

function main() {
  try {
    throw new MyCustomError('Something specific went wrong!');
  } catch (error) {
    if (error instanceof MyCustomError) {
      console.log(`Caught: ${error.name} - ${error.message}`);
    } else {
      console.log(`Caught generic error: ${error.message}`);
    }
  }
}

main();

tRPC's TRPCError

For tRPC to correctly understand and propagate errors, your custom errors should extend TRPCError from @trpc/server.

TRPCError requires an object with a code (e.g., 'NOT_FOUND', 'BAD_REQUEST') and a message. This code helps the client understand the error type.

Defining a tRPC Custom Error

Here's how you define a custom error for tRPC, ensuring it extends TRPCError and sets a relevant status code.

This example creates a UserNotFoundError. Notice we pass the tRPC code to the super() constructor.

import { TRPCError } from '@trpc/server';

class UserNotFoundError extends TRPCError {
  constructor(userId: string) {
    super({
      code: 'NOT_FOUND',
      message: `User with ID '${userId}' not found.`
    });
    this.name = 'UserNotFoundError';
  }
}

function main() {
  try {
    throw new UserNotFoundError('user-123');
  } catch (error) {
    if (error instanceof TRPCError) {
      console.log(`Error Code: ${error.code}`);
      console.log(`Error Message: ${error.message}`);
    }
  }
}

main();

Throwing Custom Errors (Backend)

Once defined, you can throw your custom error directly within your tRPC procedures (queries or mutations). tRPC will automatically catch it and send it to the client.

This allows your backend logic to signal specific issues clearly.

import { publicProcedure, router } from './trpc'; // Assume trpc setup
import { TRPCError } from '@trpc/server';

class UserNotFoundError extends TRPCError {
  constructor(userId: string) {
    super({ code: 'NOT_FOUND', message: `User ${userId} not found.` });
    this.name = 'UserNotFoundError';
  }
}

const appRouter = router({
  getUser: publicProcedure
    .input(z.string())
    .query(async ({ input: userId }) => {
      // Simulate database lookup
      if (userId === 'nonexistent') {
        throw new UserNotFoundError(userId); // Throw our custom error!
      }
      return { id: userId, name: `User ${userId}` };
    }),
});

// Note: `z` for Zod input validation is assumed here
// The router itself is not runnable without a full server context.

Frontend: Receiving Errors

On the frontend, when a tRPC procedure fails, the client-side tRPC library will throw an instance of TRPCClientError.

This error object contains the code and message from your backend TRPCError, allowing you to identify the specific issue.

Frontend: Identifying Custom Errors

To handle specific custom errors on the client, you can use a try...catch block and inspect the error object.

  • Check error.data.code: This is the most reliable way as it's directly from the TRPCError code.
  • Check error.message: Less reliable, but can be used for specific messages.
  • instanceof (with shared types): If you share the custom error class definition between client and server, you can use instanceof. This is common in monorepos.

Frontend Example: Handling UserNotFoundError

Here's how a React component (or similar frontend logic) might handle our UserNotFoundError using the error.data.code property.

This allows you to display a user-friendly message specific to the error.

import { trpc } from './utils/trpc'; // Assume trpc client setup

function UserProfile({ userId }: { userId: string }) {
  const { data, error, isLoading } = trpc.getUser.useQuery(userId);

  if (isLoading) {
    return '<p>Loading user data...</p>';
  }

  if (error) {
    if (error.data?.code === 'NOT_FOUND') {
      return `<p>User with ID <b>${userId}</b> does not exist.</p>`;
    } else {
      return `<p>An unexpected error occurred: ${error.message}</p>`;
    }
  }

  return `<h1>Welcome, ${data?.name}!</h1>`;
}

function main() {
  // This function simulates component usage.
  // In a real app, trpc.getUser.useQuery would trigger an API call.
  console.log('Simulating UserProfile for existing user...');
  // Assume UserProfile('user-123') would render 'Welcome, User user-123!'

  console.log('Simulating UserProfile for nonexistent user...');
  // Assume UserProfile('nonexistent') would render 'User with ID nonexistent does not exist.'
}

main();

Quick Check

Which of the following are good reasons to define and use custom error types in tRPC, especially when extending TRPCError?

Recap: Custom Error Types

Great job! You've learned how to leverage custom error types in tRPC:

  • Extend TRPCError: For tRPC to correctly propagate your errors.
  • Specify code: Use tRPC's error codes (e.g., 'NOT_FOUND') for standardization.
  • Throw on Backend: Signal specific issues from your procedures.
  • Catch on Frontend: Use error.data.code for precise error handling.

This approach leads to more robust and user-friendly applications by clearly communicating backend issues to the client.

자주 묻는 질문

“사용자 지정 오류 형식” 강의는 무료인가요?

네 — “사용자 지정 오류 형식” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 tRPC End-to-End Type Safe APIs 강의 전체를 잠금 해제할 수 있습니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“사용자 지정 오류 형식”에서 뭘 배우나요?

백엔드에서 사용자 지정 오류 형식을 정의하고 발생시켜 프런트엔드에 올바르게 전달합니다. 브라우저에서 직접 실행하는 실습 코드로 tRPC End-to-End Type Safe APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

tRPC End-to-End Type Safe APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 tRPC End-to-End Type Safe APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“사용자 지정 오류 형식” 강의는 얼마나 걸리나요?

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

이 tRPC End-to-End Type Safe APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 tRPC End-to-End Type Safe APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. tRPC 오류를 우아하게 처리하기
  2. 사용자 지정 오류 형식
  3. 직렬화를 위한 데이터 변환기
  4. 오류 형식 지정과 필드 수준 검증 피드백
← tRPC End-to-End Type Safe APIs(으)로 돌아가기