Özel Hata Türleri
Arka uçtan özel hata türleri tanımlayıp fırlatın ve bunların ön uca doğru biçimde aktarılmasını sağlayın.
Özel Hata Türleri, CoddyKit'te ücretsiz bir tRPC End-to-End Type Safe APIs dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, tRPC End-to-End Type Safe APIs öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. tRPC End-to-End Type Safe APIs kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
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 theTRPCErrorcode. - 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 useinstanceof. 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.codefor precise error handling.
This approach leads to more robust and user-friendly applications by clearly communicating backend issues to the client.
Sıkça Sorulan Sorular
“Özel Hata Türleri” dersi ücretsiz mi?
Evet — “Özel Hata Türleri” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve tRPC End-to-End Type Safe APIs kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. tRPC End-to-End Type Safe APIs kursu toplamda 4 dersten oluşur.
“Özel Hata Türleri” dersinde ne öğreneceğim?
Arka uçtan özel hata türleri tanımlayıp fırlatın ve bunların ön uca doğru biçimde aktarılmasını sağlayın. tRPC End-to-End Type Safe APIs ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
tRPC End-to-End Type Safe APIs öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te tRPC End-to-End Type Safe APIs, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.
“Özel Hata Türleri” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu tRPC End-to-End Type Safe APIs dersinde kod yazıp çalıştırabilir miyim?
Evet. Her tRPC End-to-End Type Safe APIs dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- tRPC Hatalarını Uygun Biçimde Ele Alma
- Özel Hata Türleri
- Serileştirme için Veri Dönüştürücüler
- Hataları Biçimlendirme ve Alan Düzeyinde Doğrulama Geri Bildirimi