Error types
TypeScript'da xato type'lari: catch'dagi unknown, instanceof Error bilan tekshirish, o'z ApiError va ValidationError class'laringiz, login misoli va getErrorMessage helper.
88-dars
Error types
catch ichidagi xato type'i unknown bo'ladi, chunki JS'da istalgan narsani throw qilish mumkin (string, son, obyekt). Shuning uchun xatoni ishlatishdan oldin uning turini tekshirasiz. Eng yaxshi usul: o'z xato class'laringizni yaratish.
Muammo
try {
await fetchJson<User>("/api/user/1");
} catch (err) {
console.log(err.message);
// ❌ 'err' is of type 'unknown'.
}
Sabab: throw "xato" yoki throw 404 ham mumkin, ularda .message yo'q.
1. instanceof Error bilan tekshirish
try {
await fetchJson<User>("/api/user/1");
} catch (err) {
if (err instanceof Error) {
console.log(err.message); // ✅
} else {
console.log("Noma'lum xato", err);
}
}
2. O'z xato class'ingiz
API xatosida faqat matn emas, status kodi ham kerak:
class ApiError extends Error {
constructor(
public status: number,
public code: string,
message: string
) {
super(message);
this.name = "ApiError";
}
}
fetchJson'ni (85-dars) yangilaymiz:
async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
const res = await fetch(url, init);
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new ApiError(res.status, body.code ?? "UNKNOWN", body.message ?? res.statusText);
}
return res.json() as Promise<T>;
}
3. Turli xatolarni ajratish
class ValidationError extends Error {
constructor(public fields: Record<string, string>) {
super("Validatsiya xatosi");
this.name = "ValidationError";
}
}
Real misol: login
async function login(email: string, password: string) {
try {
return await fetchJson<User>("/api/login", {
method: "POST",
body: JSON.stringify({ email, password }),
});
} catch (err) {
if (err instanceof ApiError) {
if (err.status === 401) return showToast("Email yoki parol noto'g'ri");
if (err.status === 429) return showToast("Ko'p urinish, keyinroq kiring");
if (err.status >= 500) return showToast("Serverda muammo");
}
if (err instanceof ValidationError) {
return showFieldErrors(err.fields); // { email: "Noto'g'ri format" }
}
if (err instanceof TypeError) {
return showToast("Internet aloqasi yo'q"); // fetch tarmoq xatosi
}
throw err; // tanimagan xatoni yashirmang
}
}
Har bir if ichida err o'sha class'ga torayadi (instanceof narrowing, 43-dars), shuning uchun err.status, err.fields xavfsiz.
4. Yordamchi funksiya
Xabarni olish ko'p kerak bo'ladi:
function getErrorMessage(err: unknown): string {
if (err instanceof Error) return err.message;
if (typeof err === "string") return err;
return "Noma'lum xato";
}
Eslab qolish uchun
catch (err)→unknown, tekshirmasdan ishlatmang.instanceofbilan xato turini aniqlang.- API uchun
ApiError(status, code) class'ini yarating. - Tarmoq uzilsa
fetch→TypeErrortashlaydi. - Tanimagan xatoni qayta
throwqiling.