0Pricing
Flutter Mobile Development · Ders

Async İçinde Hata İşleme

Ağ hatalarını ve istisnaları uygulamanızın düzgün bir şekilde yönetmesini sağlamak için eşzamansız işlemlerde güçlü hata işleme stratejileri uygulayın.

Async İçinde Hata İşleme, CoddyKit'te ücretsiz bir Flutter Mobile Development dersidir. Bu, 4 dersinin 3. 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, Flutter Mobile Development öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Flutter Mobile Development kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Handling Unpredictable Async Errors

İnternetten veri çekmek veya dosya okumak gibi eş zamansız (asenkron) işlemler doğası gereği öngörülemezdir. Başarılı olabilirler, başarısız olabilirler ve hatta zaman aşımına uğrayabilirler.

Uygulamanızın çökmesini önlemek ve sorunsuz bir kullanıcı deneyimi sunmak için sağlam hata yönetimi çok önemlidir. Bu, bu tür başarısızlıkları zarif bir şekilde yönetmenizi sağlar.

`try-catch` for Async Operations

The familiar try-catch block in Dart is your primary tool for handling exceptions in asynchronous code. When an await expression throws an error, it can be caught by an enclosing try-catch block.

  • try: Contains the code that might throw an exception.
  • catch: Catches and handles the exception if one occurs.
  • on: (Optional) Catches specific types of exceptions.

Catching a Simulated Error

Let's see try-catch in action. This example simulates a network error by throwing an Exception within an async function. Notice how catch handles it.

import 'dart:async';

Future<String> fetchData() async {
  await Future.delayed(Duration(seconds: 1));
  // Simulate a network error
  throw Exception("Failed to fetch data!");
  return "Data received"; // This line won't be reached
}

void main() async {
  print("Starting data fetch...");
  try {
    String data = await fetchData();
    print("Success: $data");
  } catch (e) {
    print("Error caught: $e");
  } finally {
    print("Fetch attempt complete.");
  }
}

Handling Specific Exception Types

Sometimes, you want to handle different types of errors in different ways. The on keyword allows you to catch specific exception types, making your error handling more precise.

For example, you might handle a SocketException (network issue) differently from a generic Exception.

Targeted Error Handling

Here, we define two types of errors: a custom NetworkException and a generic Exception. The on clause lets us provide specific handling for each.

import 'dart:async';

class NetworkException implements Exception {
  final String message;
  NetworkException(this.message);
  @override
  String toString() => 'NetworkException: $message';
}

Future<void> performNetworkCall(bool shouldFailNetwork) async {
  await Future.delayed(Duration(milliseconds: 500));
  if (shouldFailNetwork) {
    throw NetworkException("No internet connection!");
  } else {
    throw Exception("An unknown error occurred.");
  }
}

void main() async {
  print("Attempt 1: Simulate network failure");
  try {
    await performNetworkCall(true);
  } on NetworkException catch (e) {
    print("Caught specific network error: ${e.message}");
  } catch (e) {
    print("Caught generic error: $e");
  }

  print("\nAttempt 2: Simulate unknown error");
  try {
    await performNetworkCall(false);
  } on NetworkException catch (e) {
    print("Caught specific network error: ${e.message}");
  } catch (e) {
    print("Caught generic error: $e");
  }
}

Ensuring Cleanup with `finally`

The finally block is an optional part of a try-catch statement. Code inside this block will always execute, regardless of whether an exception was thrown or caught.

It's perfect for cleanup operations, like closing a file stream or dismissing a loading indicator, ensuring resources are properly managed.

Alternative: `Future.catchError`

While try-catch works well with async/await, you can also handle errors directly on a Future object using its .catchError() method. This is often used when chaining Futures or when not using await immediately.

It takes a function that will be called if the Future completes with an error.

Handling Errors with `catchError`

Here's how .catchError() can be used. Notice that the error is handled as part of the Future's completion chain, without needing an async function or await for the error handling itself.

import 'dart:async';

Future<String> getUserData() {
  return Future.delayed(Duration(seconds: 1)).then((_) {
    throw Exception("User data not found!");
    return "User data"; // Unreachable
  });
}

void main() {
  print("Fetching user data...");
  getUserData().then((data) {
    print("Success: $data");
  }).catchError((error) {
    print("Error with .catchError(): $error");
  }).whenComplete(() {
    print("User data fetch completed.");
  });
}

Good Practices for Error Handling

Effective error handling makes your app robust and user-friendly:

  • Log errors: Use a logging framework to record errors for debugging.
  • Provide feedback: Inform the user about what went wrong (e.g., "Network unavailable").
  • Retry mechanism: For transient network issues, consider offering a retry option.
  • Avoid empty catch blocks: Always handle or re-throw errors, don't just swallow them.

Async Error Handling Check

Consider the following Dart code snippet. Which statements about its error handling are true?

import 'dart:async';

Future<String> riskyOperation() async {
  await Future.delayed(Duration(milliseconds: 100));
  if (DateTime.now().second % 2 == 0) {
    throw FormatException("Invalid data format!");
  }
  return "Data processed.";
}

void main() async {
  try {
    String result = await riskyOperation();
    print("Result: $result");
  } on FormatException catch (e) {
    print("Specific error: ${e.message}");
  } catch (e) {
    print("Generic error: $e");
  } finally {
    print("Operation finished.");
  }
}

Recap: Mastering Async Errors

In this lesson, we explored how to handle errors in asynchronous Dart and Flutter applications. You learned:

  • The importance of robust error handling.
  • Using try-catch with async/await.
  • Catching specific exceptions with on.
  • Ensuring cleanup with finally.
  • An alternative: Future.catchError().
  • Best practices for building resilient apps.

Proper error handling is key to creating stable and user-friendly mobile experiences!

Sıkça Sorulan Sorular

“Async İçinde Hata İşleme” dersi ücretsiz mi?

Evet — “Async İçinde Hata İşleme” 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 Flutter Mobile Development kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Flutter Mobile Development kursu toplamda 4 dersten oluşur.

“Async İçinde Hata İşleme” dersinde ne öğreneceğim?

Ağ hatalarını ve istisnaları uygulamanızın düzgün bir şekilde yönetmesini sağlamak için eşzamansız işlemlerde güçlü hata işleme stratejileri uygulayın. Flutter Mobile Development 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.

Flutter Mobile Development öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Flutter Mobile Development, 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 3. dersidir.

“Async İçinde Hata İşleme” 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 Flutter Mobile Development dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Flutter Mobile Development 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

  1. Future'lar ve Async/Await
  2. HTTP İstekleri ve JSON
  3. Async İçinde Hata İşleme
  4. Akışlar ve Tepkisel Veriler
← Flutter Mobile Development Sayfasına Dön