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

1,091

The best and most common way to do this in Dart/Flutter, is making a custom exception class and throwing and catching them where needed

I would suggest setting up your code like this

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");
  }
}

Also, whatever library your using for http also probably has some built in error handling

Share:
1,091
fvisticot
Author by

fvisticot

Updated on December 08, 2022

Comments

  • fvisticot
    fvisticot over 1 year

    Error and Exception are available in Dart.

    Supposing I'm using a REST API to do the login, How do I need to manage the login function ?

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

    In case API is returning 200 OK :

    • Simply return true ?
    • Other suggestion ?

    In case API HTTP error 401/Unauthorized 500/ServerError or Network error (timeout or not available), what to return ?

    • Exception ?

    • Error ?

    • false (but what is the message to display on the app screen ?)