tRPC 오류를 우아하게 처리하기
tRPC 절차와 미들웨어에서 오류를 포착하고 응답하기 위한 모범 사례를 구현합니다.
tRPC 오류를 우아하게 처리하기은(는) CoddyKit의 무료 tRPC End-to-End Type Safe APIs 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 tRPC End-to-End Type Safe APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
API Errors: A Necessary Evil
In any robust API, errors are inevitable. Users might send invalid data, resources might not exist, or external services could fail.
Implementing graceful error handling is crucial for creating stable and user-friendly applications. It allows your API to respond predictably and informatively.
How tRPC Handles Errors
By default, tRPC automatically catches any JavaScript errors thrown within your procedures or middleware. It serializes them and sends them to the client.
Generic errors are often mapped to an INTERNAL_SERVER_ERROR (HTTP 500) status on the client side if not explicitly handled. Try running this example to see a generic error.
function fetchData(shouldFail: boolean) {
if (shouldFail) {
throw new Error("Something went wrong on the server!");
}
return "Data fetched successfully.";
}
function main() {
try {
console.log("Attempting to fetch (success):");
console.log(fetchData(false));
} catch (error: any) {
// This catch block demonstrates local error handling
// tRPC server would catch and serialize if not handled here
console.log(`Caught error: ${error.message}`);
}
try {
console.log("\nAttempting to fetch (fail):");
fetchData(true);
} catch (error: any) {
console.log(`Caught error: ${error.message}`);
}
}
main();Standardizing with TRPCError
To provide structured and predictable error responses, tRPC offers the TRPCError class. This is tRPC's dedicated way to throw API-specific errors.
TRPCErrorallows you to specify acode(like an HTTP status) and a human-readablemessage.- It ensures consistent error payloads, making it easier for clients to interpret and react to different error types.
Anatomy of TRPCError
When you create a TRPCError, you pass an object with a code and a message. The code maps to standard HTTP status codes (e.g., NOT_FOUND, UNAUTHORIZED).
This example shows how to throw different TRPCError types based on conditions.
import { TRPCError } from '@trpc/server';
function simulateError(type: string) {
if (type === 'not_found') {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'Resource does not exist.'
});
}
if (type === 'bad_input') {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'Invalid input provided.'
});
}
return 'No error was simulated.';
}
function main() {
try {
console.log("Simulating 'not_found' error:");
simulateError('not_found');
} catch (error: any) {
if (error instanceof TRPCError) {
console.log(`TRPC Error Code: ${error.code}`);
console.log(`TRPC Error Message: ${error.message}`);
} else {
console.log(`Generic Error: ${error.message}`);
}
}
}Handling Errors in Procedures
Your tRPC procedures contain the core business logic. It's good practice to wrap operations that might fail (like database calls or API requests) in try...catch blocks.
Inside the catch block, you can translate generic errors into specific TRPCError instances, providing clear feedback to the client.
Example: Procedure Error Handling
This example simulates a procedure trying to fetch a user from a database. It handles both a missing user and a database connection error, converting them into appropriate TRPCError types.
import { TRPCError } from '@trpc/server';
// Simulate a database call
function fetchUserFromDB(id: string) {
if (id === 'db_error') {
throw new Error("Database connection failed!");
}
if (id === '123') {
return { id: '123', name: 'Alice' };
}
return null;
}
// Simulate a tRPC query procedure
function getUserQuery(userId: string) {
try {
const user = fetchUserFromDB(userId);
if (!user) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'User not found.'
});
}
return user;
} catch (error: any) {
if (error instanceof TRPCError) {
throw error; // Re-throw tRPC errors directly
}
// Catch generic errors and convert them to TRPCError
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: `Failed to fetch user: ${error.message}`
});
}
}
function main() {
try {
console.log("Fetching user '123':");
console.log(getUserQuery('123'));
} catch (error: any) {
console.log(`Error: ${error.code} - ${error.message}`);
}
try {
console.log("\nFetching user 'db_error':");
getUserQuery('db_error');
} catch (error: any) {
console.log(`Error: ${error.code} - ${error.message}`);
}
}Error Handling in Middleware
tRPC middleware functions are executed before procedures. They are ideal for global checks like authentication, authorization, or logging.
If a middleware function throws a TRPCError, the procedure it guards will not execute, and the error will be immediately propagated to the client. This is powerful for protecting your API.
Example: Middleware Authorization Error
This middleware checks if the user has an 'admin' role. If not, it throws an UNAUTHORIZED error, preventing any subsequent procedure from running.
This ensures only authorized users can proceed.
import { TRPCError } from '@trpc/server';
// Simulate a tRPC middleware logic
// In a real tRPC app, `ctx` would contain user info
function authMiddleware(userRole: string) {
if (userRole !== 'admin') {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'You are not authorized to perform this action.'
});
}
return { success: true, message: 'Authorized' }; // Simulates `next()`
}
function main() {
console.log("Attempting with 'user' role:");
try {
authMiddleware('user');
} catch (error: any) {
if (error instanceof TRPCError) {
console.log(`Middleware Error: ${error.code} - ${error.message}`);
}
}
console.log("\nAttempting with 'admin' role:");
try {
authMiddleware('admin');
console.log("Middleware passed: User is an admin!");
} catch (error: any) {
console.log("This block should not be reached for admin.");
}
}
main();Client-Side Error Propagation
When your tRPC server throws a TRPCError, the tRPC client receives a structured error object. This object typically contains:
code: The tRPC error code (e.g., 'NOT_FOUND').message: The descriptive error message.data: Additional error data, including the HTTP status code.
This allows your frontend to react specifically to different error types, improving user experience.
Error Handling Check
Consider a tRPC procedure that fetches a blog post. If the user making the request is authenticated but does not have the necessary permissions to view that specific post, what TRPCError code would be most appropriate to throw?
Recap: Graceful Errors
You've learned how to handle errors gracefully in tRPC!
- tRPC automatically catches generic errors, but
TRPCErrorprovides structure. - Use
TRPCErrorwith specificcodes (likeNOT_FOUND,UNAUTHORIZED) and messages. - Implement
try...catchin procedures to convert generic errors intoTRPCErrors. - Leverage middleware to enforce global checks (e.g., authentication) by throwing
TRPCErrors early. - Clients receive structured error objects, enabling better frontend error handling.
자주 묻는 질문
“tRPC 오류를 우아하게 처리하기” 강의는 무료인가요?
네 — “tRPC 오류를 우아하게 처리하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 tRPC End-to-End Type Safe APIs 강의 전체를 잠금 해제할 수 있습니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“tRPC 오류를 우아하게 처리하기”에서 뭘 배우나요?
tRPC 절차와 미들웨어에서 오류를 포착하고 응답하기 위한 모범 사례를 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 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개 중 1번째 강의입니다.
“tRPC 오류를 우아하게 처리하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 tRPC End-to-End Type Safe APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 tRPC End-to-End Type Safe APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- tRPC 오류를 우아하게 처리하기
- 사용자 지정 오류 형식
- 직렬화를 위한 데이터 변환기
- 오류 형식 지정과 필드 수준 검증 피드백