Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Error handling in Flutter

Error handling in Flutter

Enzo Lizama Paredes

May 22, 2020
Tweet

More Decks by Enzo Lizama Paredes

Other Decks in Programming

Transcript

  1. Programs can go wrong for so many reasons • Invalid

    input ◦ Strings with invalid values ◦ Numbers out of range ◦ Unexpectedly null pointers exceptions • External failure ◦ File not found ◦ Timeouts • Programming errors ◦ Array out of bound ◦ Invalid state • System error ◦ Out of memory
  2. /// This is an [FlutterErrorDetails], appears instead of the red

    screen /// to avoid scare the users ErrorWidget.builder = (FlutterErrorDetails details) => CustomErrorWidget(); ... class CustomErrorWidget extends StatelessWidget { @override Widget build(BuildContext context) { // Your custom error widget } }
  3. /// This is an [FlutterErrorDetails], appears instead of the red

    screen /// to avoid scare the users ErrorWidget.builder = (FlutterErrorDetails details) => CustomErrorWidget(); ... class CustomErrorWidget extends StatelessWidget { @override Widget build(BuildContext context) { // Your custom error widget } }
  4. class Failure { final String message; final int statusCode; Failure(this.message,

    this.statusCode); @override String toString() => "Error $statusCode. $message."; }
  5. Future<List<HotelModel>> getHotels() async { try { final data = await

    http.get(_baseUrl + _endPoint); final responseList = json.decode(data.body); return [for (final hotel in responseList) HotelModel.fromJson(hotel)]; } on SocketException { throw Failure("No internet connection", 400); } on HttpException { throw Failure("Not found request", 404); } on FormatException { throw Failure("Invalid JSON format", 666); } catch (e) { throw Failure("Unknown error", 888); } }
  6. Future<List<HotelModel>> getHotels() async { try { final data = await

    http.get(_baseUrl + _endPoint); final responseList = json.decode(data.body); return [for (final hotel in responseList) HotelModel.fromJson(hotel)]; } on SocketException { throw Failure("No internet connection", 400); } on HttpException { throw Failure("Not found request", 404); } on FormatException { throw Failure("Invalid JSON format", 666); } catch (e) { throw Failure("Unknown error", 888); } }
  7. void retrieveHotels() async { try { _hotels = await repository.fetchHotels();

    } on Failure catch (e) { _failure = e; } notifyListeners(); }
  8. Catcher Catcher is Flutter plugin which automatically catches error/exceptions and

    handle them. Catcher offers mutliple way to handle errors https://pub.dev/packages/catcher