Skip to content

Commit

Permalink
FEAT: tryCatchHandler
Browse files Browse the repository at this point in the history
added tryCatchHandler

update

update

update

update

update

updated try catch handler
  • Loading branch information
juskek committed Sep 28, 2022
1 parent 86368a8 commit b74b17e
Show file tree
Hide file tree
Showing 9 changed files with 200 additions and 12 deletions.
22 changes: 21 additions & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1 +1,21 @@
TODO: Add your license here.
MIT License

Copyright (c) 2022 Kek Tech

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
29 changes: 29 additions & 0 deletions example/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import 'dart:convert';

import 'package:flutter_dev_utils/flutter_dev_utils.dart';
import 'package:logger/logger.dart';

void main() {
print(
'Run with either `dart example/main.dart` or `dart --enable-asserts example/main.dart`.');
Demo.run();
}

class Demo {
static void run() {
syncTryCatchHandler(tryFunction: () {
CallerLogger().i('It works!');
return true;
});
asyncTryCatchHandler(tryFunction: () async {
CallerLogger().i('It works!');
return true;
});
syncTryCatchHandler(
tryFunction: () => jsonDecode('notJson'),
);
asyncTryCatchHandler(
tryFunction: () => jsonDecode('notJson'),
);
}
}
7 changes: 2 additions & 5 deletions lib/flutter_dev_utils.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
library flutter_dev_utils;

/// A Calculator.
class Calculator {
/// Returns [value] plus 1.
int addOne(int value) => value + 1;
}
export 'src/try_catch_handler/sync_try_catch_handler.dart';
export 'src/try_catch_handler/async_try_catch_handler.dart';
13 changes: 13 additions & 0 deletions lib/src/logger.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import 'package:logger/logger.dart';

var utilsLogger = CallerLogger(
ignoreCallers: {
'asyncTryCatchHandler',
'syncTryCatchHandler',
},
filter: TypeFilter(
ignoreTypes: {},
ignoreLevel: Level.warning,
),
level: Level.verbose,
);
45 changes: 45 additions & 0 deletions lib/src/try_catch_handler/async_try_catch_handler.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import 'package:flutter_dev_utils/src/logger.dart';
import 'package:flutter_dev_utils/src/try_catch_handler/catch_utils.dart';

/// Asynchronous try and catch handler to reduce boilerplate
///
/// Should be called in a State file
Future<dynamic> asyncTryCatchHandler(
{required Future<dynamic> Function() tryFunction,
Map<dynamic, Future<dynamic> Function(Object e)>? catchKnownExceptions,
Future<dynamic> Function()? catchUnknownExceptions}) async {
//! Validate Catch Known
if (catchKnownExceptions != null) {
validateCatchKnownExceptions(catchKnownExceptions);
}
try {
//! Main Try
try {
return tryFunction.call();
} catch (e, s) {
//! Handle Known Errors and Exceptions

if (e is! Error || e is! Exception || catchKnownExceptions == null) {
rethrow;
} else {
Future<dynamic> Function(Object e)? callback;
catchKnownExceptions.forEach((key, value) {
if (key.runtimeType == e.runtimeType) {
callback = value;
}
});

if (callback != null) {
utilsLogger.w('Handling known exception', e, s);
return callback!.call(e);
} else {
rethrow;
}
}
}
} catch (e, s) {
//! Handle Unknown Errors and Exceptions
utilsLogger.e('Caught unknown exception', e, s);
return catchUnknownExceptions?.call();
}
}
31 changes: 31 additions & 0 deletions lib/src/try_catch_handler/catch_utils.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
void validateCatchKnownExceptions(
Map<dynamic, dynamic Function(Exception e)?> catchKnownExceptions) {
/// Type check for catchKnownExceptions map: key should be error or exception
///
/// Note that AssertionError.runtimeType returns Type, while
/// AssertionError().runtimeType returns Type
catchKnownExceptions.forEach((key, value) {
if (key is! Error && key is! Exception) {
throw ArgumentError(
'''Key passed to catchKnownExceptions should be of Error or Exception type, not ${key.runtimeType}.
\nTry using an instantiation of the error instead of the error,
e.g., AssertionError() instead of AssertionError.
This is necessary because AssertionError.runtimeType returns Type, while
AssertionError().runtimeType returns AssertionEror''');
}
});

/// Duplicate check
///
/// Since an instantiation of Error/Exception is passed instead of the type,
/// need to check for duplicate keys
Set keyTypes = {};
catchKnownExceptions.forEach((key, value) {
if (!keyTypes.contains(key.runtimeType)) {
keyTypes.add(key.runtimeType);
} else {
throw ArgumentError(
'''Duplicate key passed to catchKnownExceptions: ${key.runtimeType}''');
}
});
}
45 changes: 45 additions & 0 deletions lib/src/try_catch_handler/sync_try_catch_handler.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import 'package:flutter_dev_utils/src/logger.dart';
import 'package:flutter_dev_utils/src/try_catch_handler/catch_utils.dart';

/// Synchronous try and catch handler to reduce boilerplate
///
/// Should be called in a State file
dynamic syncTryCatchHandler(
{required dynamic Function() tryFunction,
Map<dynamic, dynamic Function(Object e)>? catchKnownExceptions,
dynamic Function()? catchUnknownExceptions}) {
//! Validate Catch Known
if (catchKnownExceptions != null) {
validateCatchKnownExceptions(catchKnownExceptions);
}
try {
//! Main Try
try {
return tryFunction.call();
} catch (e, s) {
//! Handle Known Errors and Exceptions

if (e is! Error || e is! Exception || catchKnownExceptions == null) {
rethrow;
} else {
dynamic Function(Object e)? callback;
catchKnownExceptions.forEach((key, value) {
if (key.runtimeType == e.runtimeType) {
callback = value;
}
});

if (callback != null) {
utilsLogger.w('Handling known exception', e, s);
return callback!.call(e);
} else {
rethrow;
}
}
}
} catch (e, s) {
//! Handle Unknown Errors and Exceptions
utilsLogger.e('Caught unknown exception', e, s);
return catchUnknownExceptions?.call();
}
}
10 changes: 9 additions & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
name: flutter_dev_utils
description: A new Flutter package project.
version: 0.0.1
homepage:
homepage: https://github.com/Kek-Tech/flutter_dev_utils

publish_to: none

environment:
sdk: '>=2.18.0-271.7.beta <3.0.0'
Expand All @@ -10,6 +12,12 @@ environment:
dependencies:
flutter:
sdk: flutter
logger:
git:
url: https://github.com/Kek-Tech/logger.git
ref: master



dev_dependencies:
flutter_test:
Expand Down
10 changes: 5 additions & 5 deletions test/flutter_dev_utils_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_dev_utils/flutter_dev_utils.dart';

void main() {
test('adds one to input values', () {
final calculator = Calculator();
expect(calculator.addOne(2), 3);
expect(calculator.addOne(-7), -6);
expect(calculator.addOne(0), 1);
test('test_async_try_catch_handler', () {
expect('a', 'a');
});
test('test_sync_try_catch_handler', () {
expect('a', 'a');
});
}

0 comments on commit b74b17e

Please sign in to comment.