import 'dart:async';

import '../base/base_response.dart';

class HttpHandler {
  HttpHandler._();

  static FutureOr<T> Function(BaseResponse<T> value) handle<T>(
      bool allowEmptyData) {
    return (BaseResponse<T> response) {
      if (response.code == 0) {
        if (response.data != null || allowEmptyData) {
          return response.data == null ? Future.value() : response.data!;
        } else {
          throw Exception('data is null');
        }
      } else {
        throw ServerErrorException(response.code, response.message);
      }
    };
  }
}

class ServerErrorException implements Exception {
  final int? code;
  final String? message;

  ServerErrorException(this.code, this.message);

  @override
  String toString() {
    return 'ServerErrorException: code: $code, message: $message';
  }
}
