Share
Embed
Transcript
18 slides
-
KotlinConf 2019: Error Handling Strategies for Kotlin Programs by Nat
Pryce & Duncan McGregor What is failure? -
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 -
https://dart.dev/guides/libraries/library-tour#exceptions Exceptions are considered conditions that you can plan ahead
for and catch. Errors are conditions that you don’t expect or plan for. -
FlutterError.onError = (FlutterErrorDetails details) { FlutterError.dumpErrorToConsole(details); if (kReleaseMode) { exit(1);
// Report problem and track it } }; -
/// 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 } } -
/// 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 } } -
class Failure { final String message; final int statusCode; Failure(this.message,
this.statusCode); @override String toString() => "Error $statusCode. $message."; } -
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); } } -
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); } } -
void retrieveHotels() async { try { _hotels = await repository.fetchHotels();
} on Failure catch (e) { _failure = e; } notifyListeners(); } -
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