http_handler.dart 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import 'dart:async';
  2. import 'package:location/data/repositories/account_repository.dart';
  3. import '../base/base_response.dart';
  4. import '../data/consts/error_code.dart';
  5. class HttpHandler {
  6. HttpHandler._();
  7. static FutureOr<T> Function(BaseResponse<T> value) handle<T>(
  8. bool allowEmptyData) {
  9. return (BaseResponse<T> response) {
  10. if (response.code == 0) {
  11. if (response.data != null || allowEmptyData) {
  12. return response.data == null ? Future.value() : response.data!;
  13. } else {
  14. throw Exception('data is null');
  15. }
  16. } else {
  17. if (response.code == ErrorCode.noLoginError) {
  18. AccountRepository.getInstance().logout();
  19. }
  20. throw ServerErrorException(response.code, response.message);
  21. }
  22. };
  23. }
  24. }
  25. class ServerErrorException implements Exception {
  26. final int? code;
  27. final String? message;
  28. ServerErrorException(this.code, this.message);
  29. @override
  30. String toString() {
  31. return 'ServerErrorException: code: $code, message: $message';
  32. }
  33. }