[flutter] Dio를 사용하여 서버와의 통신 중 예외가 발생한 경우 처리하는 방법을 알려주세요.
Dio는 Flutter 앱에서 서버와의 통신을 용이하게 해주는 HTTP 클라이언트 라이브러리입니다. 서버로의 요청 중에 네트워크 오류나 서버 측 예외가 발생할 수 있는데, Dio를 사용하여 이러한 예외를 적절히 처리하는 방법을 알아보겠습니다.
네트워크 오류 처리
Dio를 사용하여 서버에 요청을 보내다가 네트워크 오류가 발생하는 경우에는 DioError
예외가 발생합니다. 이 경우에는 try-catch
문을 사용하여 예외를 처리할 수 있습니다.
try {
Response response = await dio.get('https://example.com/api/data');
// 서버 응답 처리
} on DioError catch (e) {
if (e.response != null) {
// 서버 응답이 있지만 오류가 있는 경우 처리
print(e.response.data);
print(e.response.headers);
print(e.response.request);
} else {
// 서버 응답이 없는 경우 (네트워크 오류 등) 처리
print(e.request);
print(e.message);
}
}
서버 측 오류 처리
서버 측에서 반환한 HTTP 상태 코드가 400 이상인 경우에는 DioError
예외가 발생합니다. 이 경우에도 try-catch
문으로 예외를 처리할 수 있습니다.
try {
Response response = await dio.get('https://example.com/api/data');
// 서버 응답 처리
if (response.statusCode != 200) {
// 서버 측 오류 처리
print('서버 측 오류: ${response.statusCode}');
print(response.data);
}
} on DioError catch (e) {
if (e.response != null) {
// 서버 응답이 있는 경우 처리
print(e.response.data);
} else {
// 서버 응답이 없는 경우 (네트워크 오류 등) 처리
print(e.request);
print(e.message);
}
}
참고 자료
- Dio 패키지: https://pub.dev/packages/dio
- Flutter HTTP 요청: https://flutter.dev/docs/cookbook/networking/fetch-data
Dio를 사용하여 서버와의 통신 중 발생하는 예외를 적절히 처리함으로써 안정적인 네트워크 통신을 구현할 수 있습니다.