Skip to content

Instantly share code, notes, and snippets.

@xsahil03x
Created October 23, 2019 18:36
Show Gist options
  • Save xsahil03x/21d124ce8d5697ce890b8c76adc638fb to your computer and use it in GitHub Desktop.
Save xsahil03x/21d124ce8d5697ce890b8c76adc638fb to your computer and use it in GitHub Desktop.
Error Handling
@immutable
class ApiException implements Exception {
final String _message;
final String _prefix;
String get message => _message;
const ApiException([this._message, this._prefix]);
String toString() => "$_prefix$_message";
}
class FetchDataException extends ApiException {
FetchDataException([String message])
: super(message, "Error During Communication: ");
}
class BadRequestException extends ApiException {
BadRequestException([message]) : super(message, "Invalid Request: ");
}
class UnauthorisedException extends ApiException {
UnauthorisedException([message]) : super(message, "Unauthorised: ");
}
class InvalidInputException extends ApiException {
InvalidInputException([String message]) : super(message, "Invalid Input: ");
}
abstract class BaseState<T extends StatefulWidget> extends State<T> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
GlobalKey<ScaffoldState> get scaffoldKey => _scaffoldKey;
BlocBase baseBloc;
setBaseBloc(BlocBase baseBloc) {
this.baseBloc = baseBloc;
_listenToErrors();
}
_listenToErrors() {
baseBloc?.baseError?.listen((e) {
_showSnackBar(e.exception);
});
}
_showSnackBar(Exception exception) {
_scaffoldKey.currentState.hideCurrentSnackBar();
_scaffoldKey.currentState
.showSnackBar(SnackBar(content: Text('$exception')));
}
}
abstract class BlocBase {
final _prefHelper = locator<AppPreferencesHelper>();
final _subjectBaseError = BehaviorSubject<CaughtException>();
Observable<CaughtException> get baseError => _subjectBaseError.stream;
showError(CaughtException error) => _subjectBaseError.sink.add(error);
User getCurrentUser() {
final user = json.decode(_prefHelper.getUserData());
return User.fromApiJson(user);
}
@mustCallSuper
void dispose() {
_subjectBaseError?.close();
}
}
typedef AsyncCallback<T> = Future<Result<T>> Function();
Future<Result<T>> safeApiCall<T>(
AsyncCallback<T> call, String errorMessage) async {
try {
return await call();
} catch (e, stacktrace) {
// An exception was thrown when calling the API
// so we're returning a failure
return Result.failure(e, stacktrace);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment