TypeScript xatoliklarni boshqarish


Ishonchli TypeScript ilovalarini yaratish uchun xatolarni ishonchli boshqarish juda muhimdir.

Ushbu qo‘llanma asosiy sinab ko‘rish/tutishdan tortib, ilg‘or xatolarni boshqarish naqshlarigacha bo‘lgan hamma narsani qamrab oladi.


ULASHISH

Asosiy xatolarni boshqarish

Bloklarni sinab ko‘ring/ushlang

TypeScript-da xatolarni qayta ishlash asoslari:

function divide(a: number, b: number): number {
  if (b === 0) {
    throw new Error('Division by zero');
  }
  return a / b;
}

try {
  const result = divide(10, 0);
  console.log(result);
} catch (error) {
  console.error('An error occurred:', error.message);
}
O‘zingiz sinab ko‘ring »

TypeScript 4.0+ Eslatma

TypeScript 4.0 va undan keyingi versiyalarida unknown turi catch o‘zgaruvchilari uchun standart tur hisoblanadi. Xususiyatlarga kirishdan oldin har doim turni toraytiring.


Maxsus xato sinflari

Maxsus xato sinflarini yaratish

Domenga xos xatolar yaratish uchun o‘rnatilgan Error sinfini kengaytiring:

class ValidationError extends Error {
  constructor(message: string, public field?: string) {
    super(message);
    this.name = 'ValidationError';
    // Restore prototype chain
    Object.setPrototypeOf(this, ValidationError.prototype);
  }
}

class DatabaseError extends Error {
  constructor(message: string, public code: number) {
    super(message);
    this.name = 'DatabaseError';
    Object.setPrototypeOf(this, DatabaseError.prototype);
  }
}

// Usage
function validateUser(user: any) {
  if (!user.name) {
    throw new ValidationError('Name is required', 'name');
  }
  if (!user.email.includes('@')) {
    throw new ValidationError('Invalid email format', 'email');
  }
}
O‘zingiz sinab ko‘ring »


Xatolar uchun soqchilarni yozing

Xatolarni boshqarish uchun Predikatlar turi

Turli xil xato turlari bilan xavfsiz ishlash uchun turdagi himoya vositalarini yarating:

// Type guards
function isErrorWithMessage(error: unknown): error is { message: string } {
  return (
    typeof error === 'object' &&
    error !== null &&
    'message' in error &&
    typeof (error as Record).message === 'string'
  );
}

function isValidationError(error: unknown): error is ValidationError {
  return error instanceof ValidationError;
}

// Usage in catch block
try {
  validateUser({});
} catch (error: unknown) {
  if (isValidationError(error)) {
    console.error(`Validation error in ${error.field}: ${error.message}`);
  } else if (isErrorWithMessage(error)) {
    console.error('An error occurred:', error.message);
  } else {
    console.error('An unknown error occurred');
  }
}
O‘zingiz sinab ko‘ring »

Tasdiqlash namunasini yozing

Xatolarni yanada murakkabroq hal qilish uchun turni tasdiqlash funksiyasidan foydalanishni ko‘rib chiqing:

function assertIsError(error: unknown): asserts error is Error {
  if (!(error instanceof Error)) {
    throw new Error('Caught value is not an Error instance');
  }
}

try {
  // ...
} catch (error) {
  assertIsError(error);
  console.error((error as Error).message); // TypeScript now knows error is Error
}

Asinxron xatolarni boshqarish

async/await xatolarini qayta ishlash

async/await kodida xatolarni to‘g‘ri qayta ishlash uchun await chaqiruvlarini try/catch bloklariga o‘rash talab etiladi:

interface User {
  id: number;
  name: string;
  email: string;
}

// Using async/await with try/catch
async function fetchUser(userId: number): Promise {
  try {
    const response = await fetch(`/api/users/${userId}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json() as User;
  } catch (error) {
    if (error instanceof Error) {
      console.error('Failed to fetch user:', error.message);
    }
    throw error; // Re-throw to allow caller to handle
  }
}

// Using Promise.catch() for error handling
function fetchUserPosts(userId: number): Promise {
  return fetch(`/api/users/${userId}/posts`)
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.json();
    })
    .catch(error => {
      console.error('Failed to fetch posts:', error);
      return []; // Return empty array as fallback
    });
}
O‘zingiz sinab ko‘ring »

Ko‘rib chiqilmagan Promiselarni rad etish

Promiselarni rad etish to‘g‘risidagi ogohlantirishlarni oldini olish uchun har doim Promiselarni rad etish bilan shug‘ullaning:

// Bad: Unhandled promise rejection
fetchData().then(data => console.log(data));

// Good: Handle both success and error cases
fetchData()
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

// Or use void for intentionally ignored errors
void fetchData().catch(console.error);

React’dagi xato chegaralari

React xatosi chegara komponenti

React komponentlar daraxtlarida JavaScript xatolarini ushlash uchun xato chegarasini yarating:

import React, { Component, ErrorInfo, ReactNode } from 'react';

interface ErrorBoundaryProps {
  children: ReactNode;
  fallback?: ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error?: Error;
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  public state: ErrorBoundaryState = {
    hasError: false
  };

  public static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    return { hasError: true, error };
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('Uncaught error:', error, errorInfo);
    // Log to error reporting service
  }

  public render() {
    if (this.state.hasError) {
      return this.props.fallback || (
        <div className="error-boundary">
          <h2>Something went wrong</h2>
          <p>{this.state.error?.message}</p>
          <button onClick={() => this.setState({ hasError: false })}>
            Try again
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

// Usage
function App() {
  return (
    <ErrorBoundary fallback={<div>Oops! Something broke.</div>}>
      <MyComponent />
    </ErrorBoundary>
  );
}

Eng yaxshi amaliyotlar

Har doim xatolar bilan shug‘ullaning

Hech qachon ushlash bloklarini bo‘sh qoldirmang.

Hech bo‘lmaganda xatoni qayd qiling:

// Bad: Silent failure
try { /* ... */ } catch { /* empty */ }

// Good: At least log the error
try { /* ... */ } catch (error) {
  console.error('Operation failed:', error);
}

Maxsus xato turlaridan foydalaning

Turli xil xato stsenariylari uchun maxsus xato sinflarini yarating:

class NetworkError extends Error {
  constructor(public status: number, message: string) {
    super(message);
    this.name = 'NetworkError';
  }
}

class ValidationError extends Error {
  constructor(public field: string, message: string) {
    super(message);
    this.name = 'ValidationError';
  }
}

Xatolarni to‘g‘ri darajada hal qiling

Qayta tiklash yoki yaxshi foydalanuvchi tajribasini taqdim etish uchun yetarli kontekstga ega bo‘lgan xatolarni hal qiling:

// In a data access layer
async function getUser(id: string): Promise {
  const response = await fetch(`/api/users/${id}`);
  if (!response.ok) {
    throw new NetworkError(response.status, 'Failed to fetch user');
  }
  return response.json();
}

// In a UI component
async function loadUser() {
  try {
    const user = await getUser('123');
    setUser(user);
  } catch (error) {
    if (error instanceof NetworkError) {
      if (error.status === 404) {
        showError('User not found');
      } else {
        showError('Network error. Please try again later.');
      }
    } else {
      showError('An unexpected error occurred');
    }
  }
}

Umumiy tuzoqlar

Promiselarni rad etish bilan shug‘ullanmaslik

Promiselarni rad etish to‘g‘risidagi ogohlantirishlarni oldini olish uchun har doim Promiselarni rad etish bilan shug‘ullaning:

// Bad: Unhandled promise rejection
fetchData();

// Good: Handle the rejection
fetchData().catch(console.error);

To‘g‘ri turni toraytirmasdan ushlash

TypeScript 4.0+ da ushlangan xatolar unknown tipidagi:

// Bad: Error is of type 'unknown'
try { /* ... */ } catch (error) {
  console.log(error.message); // Error: Property 'message' does not exist on type 'unknown'
}

// Good: Narrow the type
try { /* ... */ } catch (error) {
  if (error instanceof Error) {
    console.log(error.message); // OK
  }
}

Yutishdagi xatolar

To‘g‘ri ishlov bermasdan, xatolarni jimgina ushlash va e’tiborsizlik qilishdan saqlaning:

// Bad: Error is silently ignored
function saveData(data: Data) {
  try {
    database.save(data);
  } catch {
    // Ignore
  }
}

// Better: Log the error and/or notify the user
function saveData(data: Data) {
  try {
    database.save(data);
  } catch (error) {
    console.error('Failed to save data:', error);
    showError('Failed to save data. Please try again.');
  }
}

Xulosa

TypeScript-da xatolarni samarali boshqarish quyidagilarni o‘z ichiga oladi:

  • Sinxron kod uchun try/catch bloklaridan foydalanish
  • .catch() yoki try/catch bilan async/await bilan va’dalarni rad qilish
  • Domenga xos xatolar uchun maxsus xato sinflarini yaratish
  • Xato obyektlari bilan xavfsiz ishlash uchun turdagi himoya vositalaridan foydalanish
  • Ilovangizdagi tegishli darajadagi xatolar bilan ishlash
  • Foydalanuvchilarga mazmunli xato xabarlarini taqdim etish

Ushbu amaliyotlarga rioya qilish orqali siz yanada mustahkam va xizmat ko‘rsatish mumkin bo‘lgan TypeScript ilovalarini yaratishingiz mumkin.




W3Schools Pathfinder

Yutuqlaringizni kuzating – bu bepul!