如何 return 在 flutter 中捕获异常

How to return catch exception in flutter

我正在研究 api 的错误处理。我想如果 api 崩溃了,那么它会在 UI.

中显示类似这样的消息“服务器已关闭”

我创建了一个 class,其中我正在创建 api 的方法,这里是 getBooks 方法,如果我修改 api url 然后它打印这个 Exception,我想要 UI。问题是 getBooks return 类型是 List<Book>> 所以我们不能 return 这个异常,任何解决方案如何做到这一点?

Exception
E/flutter (12924): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Exception

这是我的 api 代码

class BooksApi {
  static Future<List<Book>> getBooks(String query) async {
    try {
      final url = Uri.parse(
          'https://gist.githubusercontent.com/JohannesMilke/d53fbbe9a1b7e7ca2645db13b995dc6f/raw/eace0e20f86cdde3352b2d92f699b6e9dedd8c70/books.json');
      final response = await http.get(url);

      if (response.statusCode == 200) {
        final List books = json.decode(response.body);

        return books.map((json) => Book.fromJson(json)).where((book) {
          final titleLower = book.title.toLowerCase();
          final authorLower = book.author.toLowerCase();
          final searchLower = query.toLowerCase();

          return titleLower.contains(searchLower) ||
              authorLower.contains(searchLower);
        }).toList();
      } else {
        throw Exception;
      }
    } catch (e) {
      print("e");
      print(e);
      
       
    }
  
    throw Exception;
  }
}

并称其为

Future init() async {
    setState(() {
      isLoading = true;
    });
    var books = await BooksApi.getBooks(query); //this
    
    var response = await obj.getProduct();
    print(response);
    setState(() => this.books = books);
    setState(() {
      isLoading = false;
    });
  }

您可以使用 thenonError 处理错误:

await BooksApi.getBooks(query).then((books) async {
  setState(() => {
    this.books = books;
    this.isLoading = false;
  })
}, onError: (error) {
  // do something with error
});

或简单的 try-catch(您可以像在同步代码中一样编写 try-catch 子句)。

参见 handling errors

您也可以使用 catchError 您不使用的 ID async/await :

BooksApi.getBooks(query).then((books) { 
  setState(() => {
    this.books = books;
    this.isLoading = false;
  })
}).catchError((error, stackTrace) {
  print("error is: $error");
});

futures error handling

尝试用 try and catch 包裹 'var books = await BooksApi.getBooks(query)'。

...
try {
   var books = await BooksApi.getBooks(query);
} catch (e) {
   // To do for UI
}
...

对于api,你需要做这样的事情:

APIModel{
  final int code;
// or a success flag
// final bool success;
final String message;
final List<Book> data;
APIModel({this.code,this.message,this.data});
}

也就是说,每个api都有自己的codemessagedata字段。
当您请求时,您可以检查您的 codesuccess:

var response = await request(params);
isLoading = false;
if(response.code == 0){}
// or
if(response.success){
  // do what you want
}
else {
 Toast.show(response.message);
}

您可以使用 build_runnerjson_serializable