해당 게시글은 유데미 'Learn Flutter MVVM Architecture | Build Weather App' 강의를 보고 작성하였습니다.
MVVM 구조에서 Data 폴더는 애플리케이션의 데이터 레이어를 담당한다. 이 폴더의 주요 역할은 다음과 같다.
이번에는 데이터 Data 폴더 내에서 날씨 API 구현에 있어서 데이터 관련 작업 중 발생할 수 있는 예외 상황들을 정의하고 관리하는 코드를 작성하였다. 이를 통해 애플리케이션의 유지보수성을 향상시킬 수 있다.
Data 폴더 내부에 app_exception.dart 파일을 생성한다. 해당 코드는 다음과 같은 에러들을 처리할 수 있다.
InternetException : 사용자의 장치가 인터넷에 연결되어 있지 않을 때, 날씨 데이터를 가져오려고 시도하면 InternetException이 발생 가능 -> 앱이 인터넷에 접속할 수 없음을 사용자에게 알리는 데 사용.
RequestTimeOut: API 요청이 지정된 시간 내에 완료되지 않을 경우, RequestTimeOut 예외가 발생 가능 -> 서버 응답이 지연되고 있음을 사용자에게 알리는 데 사용
ServerError : API 서버 측에서 오류가 발생할 경우, ServerError 예외를 사용하여 이를 처리 -> 서버 측 문제로 데이터를 가져올 수 없음을 사용자에게 알리는 데 사용
InvalidUrlException : API 요청 시 잘못된 URL을 사용하게 되면, InvalidUrlException이 발생 가능. -> 개발자가 API 엔드포인트를 잘못 설정했음을 나타냄
FetchDataException : API로부터 올바른 데이터를 가져오는 데 실패했을 때 FetchDataException을 사용 -> 데이터가 없거나, 손상되었거나, 예상과 다른 형식일 때 발생
class AppExceptions implements Exception{
final String? _prefix; // _ : means private
final String? _message; // final : non changeable
AppExceptions([this._prefix, this._message]);
String toString(){
//TODO: implements toString
return '$_prefix$_message';
}
}
class InternetException extends AppExceptions{
InternetException([String? message]) : super(message,'Internet Error Issue');
}
class RequestTimeOut extends AppExceptions{
RequestTimeOut([String? message]) : super(message, 'The request has timed out');
}
class ServerError extends AppExceptions{
ServerError([String? message]) : super(message, 'An internal server error occured');
}
class InvalidUrlException extends AppExceptions{
InvalidUrlException([String? message]) : super(message, 'The URL provided is invalid');
}
class FetchDataException extends AppExceptions{
FetchDataException([String? message]) : super(message,'Failed to fetch data from the server');
}