如何在顫振中返回捕獲異常

編碼時間

我正在處理 api 的錯誤處理。我希望如果 api 崩潰,那麼它會在 UI 中顯示“服務器已關閉”這樣的消息。

我創建了一個類,我在其中創建 api 的getBooks方法,如果我修改了方法,api url那麼它正在打印這個Exception,我希望它在 UI 中。問題是getBooks返回類型是List<Book>>所以我們不能返回這個異常,有什麼解決辦法嗎?

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;
    });
  }
燕39

您可以使用then處理錯誤onError

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

或一個簡單的 try-catch(您可以像在同步代碼中一樣編寫 try-catch 子句)。

請參閱處理錯誤

您還可以使用catchError不使用的 id async/ await

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

請參閱期貨錯誤處理

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章