NetworkingMedium30 XP4 min read
How do you handle network errors properly in Flutter?
TL;DR: Wrap API calls in try/catch, handle DioException types specifically (timeout, cancel, response), and return a Result<T>/Either<Failure, T> type to propagate errors to the UI layer cleanly without exceptions.
Full Answer
Throwing exceptions across layers (repository → use case → UI) is fragile. The functional Result/Either pattern makes errors first-class citizens.
DioException Types
- ▸DioExceptionType.connectionTimeout / sendTimeout / receiveTimeout
- ▸DioExceptionType.cancel: User or code cancelled the request
- ▸DioExceptionType.badResponse: Server returned 4xx/5xx
- ▸DioExceptionType.connectionError: No internet, DNS failure
🎯
Use fpdart or dartz for Either<Failure, Success>. Or create a simple sealed Result class — no dependency needed for most apps.
Code Examples
dartResult type pattern with Dio
Output
// UI receives Success(questions) or Failure('No internet connection')
// No uncaught exceptions propagating up the stackCommon Mistakes
- ✗Catching Exception instead of DioException — misses Dio-specific error information
- ✗Showing raw exception messages to users — always map to user-friendly strings
Interview Tip
💡
The Result pattern separates 'error occurred' from 'what kind of error'. Show you understand this vs exceptions, which unwind the call stack unpredictably.
#error-handling#dio-exception#result-type#either