簡體   English   中英

在Dart中管理登錄/功能錯誤的最佳做法是什么?

[英]What is the best practice to manage login / functions errors in Dart?

Dart中提供了錯誤和異常。

假設我使用REST API進行登錄,我如何管理登錄功能?

Future<bool>login(String email,String password) async

如果API返回200 OK:

  • 簡單地回歸真實?
  • 其他建議?

如果API HTTP錯誤401 /未授權500 / ServerError或網絡錯誤(超時或不可用),返回什么?

  • 例外?

  • 錯了?

  • false(但應用程序界面上顯示的消息是什么?)

在Dart / Flutter中執行此操作的最佳和最常見的方法是創建自定義異常類並在需要時拋出並捕獲它們

我建議像這樣設置你的代碼

class CustomException implements Exception {
  String message;
  CustomException(this.message);
}

Future<bool>login(String email,String password) async {
  try {
    //Throwing an Exception if something goes wrong
    throw CustomException('This is my first custom exception');
  } on CustomException {
    //Catching and handling the exception if it is thrown
    //You could throw up a snackbar or a dialog here as well
    print("Error handling");
  }
}

此外,您使用http的任何庫也可能有一些內置的錯誤處理

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM