http_handler.dart 1.1 KB

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