Tillitsdone
down Scroll to discover

Error Handling with Dio in Flutter Apps

Learn how to implement robust error handling in Flutter applications using Dio HTTP client.

Discover best practices for handling network errors, timeouts, and creating custom error handlers.
thumbnail

A modern abstract geometric pattern resembling network connections and data flow featuring metallic silver and bright white interconnected lines against a navy blue background captured from a top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Error Handling with Dio in Flutter Applications

In the world of Flutter development, making HTTP requests is a fundamental part of building modern applications. While Dio is an excellent HTTP client for Flutter, proper error handling is crucial for creating robust and user-friendly apps. Let’s dive into how we can implement effective error handling with Dio.

Understanding Dio Errors

When working with Dio, we encounter different types of errors that need to be handled appropriately. These can range from network connectivity issues to server-side errors.

Abstract light rays piercing through geometric shapes bright golden rays contrasting against white background photographed from a diagonal angle creating depth and dimension high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

try {
final response = await dio.get('/api/data');
} on DioException catch (e) {
if (e.type == DioExceptionType.connectionTimeout) {
print('Connection timed out');
} else if (e.type == DioExceptionType.connectionError) {
print('No internet connection');
}
}

Creating a Custom Error Handler

To maintain clean and reusable code, it’s recommended to create a dedicated error handler class that can manage different types of errors consistently across your application.

class DioErrorHandler {
static String handleError(DioException error) {
switch (error.type) {
case DioExceptionType.connectionTimeout:
return 'Connection timed out';
case DioExceptionType.sendTimeout:
return 'Request timed out';
case DioExceptionType.connectionError:
return 'No internet connection';
case DioExceptionType.badResponse:
return _handleBadResponse(error.response?.statusCode);
default:
return 'Something went wrong';
}
}
static String _handleBadResponse(int? statusCode) {
switch (statusCode) {
case 400:
return 'Bad request';
case 401:
return 'Unauthorized';
case 404:
return 'Not found';
case 500:
return 'Internal server error';
default:
return 'Server error';
}
}
}

Implementing Error Interceptors

Modern concrete architecture with clean lines and geometric patterns featuring bright red accents against pale concrete surfaces shot from a low angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Dio provides powerful interceptor capabilities that allow us to handle errors globally. This is particularly useful for consistent error handling across your entire application.

dio.interceptors.add(
InterceptorsWrapper(
onError: (DioException error, handler) {
// Log the error
logger.e('API Error: ${error.message}');
// Transform the error message
final errorMessage = DioErrorHandler.handleError(error);
// Show user-friendly message
showErrorSnackBar(errorMessage);
return handler.next(error);
},
),
);

Best Practices for Error Handling

  1. Always handle timeout scenarios
  2. Implement retry mechanisms for failed requests
  3. Show user-friendly error messages
  4. Log errors for debugging purposes
  5. Handle offline scenarios gracefully
Future\<T\> makeApiRequest\<T\>(Future\<T\> Function() request) async {
try {
return await request();
} on DioException catch (e) {
final errorMessage = DioErrorHandler.handleError(e);
throw CustomException(errorMessage);
} catch (e) {
throw CustomException('An unexpected error occurred');
}
}

By implementing proper error handling, your Flutter applications will become more resilient and provide a better user experience. Remember to always test your error handling implementation with different scenarios to ensure it works as expected.

A flowing abstract nebula shape with bright cyan and metallic gold colors swirling together against a deep black background captured from a wide-angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svgicons/flutter.svg
Talk with CEO
Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.