如何在飞镖中从未来返回错误



在我的颤振应用程序中,我有一个处理http请求并返回解码数据的未来。但是我希望能够通过.catchError()处理程序获得status code != 200发送错误。

这是未来:

Future<List> getEvents(String customerID) async {
  var response = await http.get(
    Uri.encodeFull(...)
  );
  if (response.statusCode == 200){
    return jsonDecode(response.body);
  }else{
    // I want to return error here 
  }
}

当我调用这个函数时,我希望能够得到这样的错误:

getEvents(customerID)
.then(
  ...
).catchError(
  (error) => print(error)
);

抛出错误/异常:

可以使用 returnthrow 引发错误或异常。

  • 使用return
    Future<void> foo() async {
      if (someCondition) {
        return Future.error('FooError');
      }
    }
    
  • 使用throw
    Future<void> bar() async {
      if (someCondition) {
        throw Exception('BarException');
      }
    }
    
<小时 />

捕获错误/异常:

您可以使用catchErrortry-catch块来捕获错误或异常。

  • 使用catchError
    foo().catchError(print);
    
  • 使用try-catch
    try {
      await bar();
    } catch (e) {
      print(e);
    }
    
您可以使用

throw

Future<List> getEvents(String customerID) async {
  var response = await http.get(
    Uri.encodeFull(...)
  );
  if (response.statusCode == 200){
    return jsonDecode(response.body);
  }else{
    // I want to return error here 
       throw("some arbitrary error"); // error thrown
  }
}

解决此问题的另一种方法是使用 dartz 包。

如何使用它的示例如下所示

import 'package:dartz/dartz.dart';
abstract class Failure {}
class ServerFailure extends Failure {}
class ResultFailure extends Failure {
  final int statusCode;
  const ResultFailure({required this.statusCode});
}
FutureOr<Either<Failure, List>> getEvents(String customerID) async {
  try {
    final response = await http.get(
      Uri.encodeFull(...)
    );
    if (response.statusCode == 200) {
      return Right(jsonDecode(response.body));
    } else {
      return Left(ResultFailure(statusCode: response.statusCode)); 
    }
  }
  catch (e) {
    return Left(ServerFailure());  
  }
}
main() async {
  final result = await getEvents('customerId');
  result.fold(
    (l) => print('Some failure occurred'),
    (r) => print('Success')
  );
}

如果要读取错误对象,可以像这样返回错误数据:

response = await dio.post(endPoint, data: data).catchError((error) {
  return error.response;
});
return response;

//POST

Future<String> post_firebase_async({String? path , required Product product}) async {
    final Uri _url = path == null ? currentUrl: Uri.https(_baseUrl, '/$path');
    print('Sending a POST request at $_url');
    final response = await http.post(_url, body: jsonEncode(product.toJson()));
    if(response.statusCode == 200){
      final result = jsonDecode(response.body) as Map<String,dynamic>;
      return result['name'];
    }
    else{
      //throw HttpException(message: 'Failed with ${response.statusCode}');
      return Future.error("This is the error", StackTrace.fromString("This is its trace"));
    }
  }

以下是调用方法:

  final result = await _firebase.post_firebase_async(product: dummyProduct).
  catchError((err){
    print('huhu $err');
  });

最新更新