https://github.com/simphotonics/exception_templates
Dart exception and error classes with generic type. Enables throwing and catching exceptions based on their type argument.
https://github.com/simphotonics/exception_templates
catch color-output dart error-handling exception exception-handling flutter generics parameterized throw
Last synced: 17 days ago
JSON representation
Dart exception and error classes with generic type. Enables throwing and catching exceptions based on their type argument.
- Host: GitHub
- URL: https://github.com/simphotonics/exception_templates
- Owner: simphotonics
- License: bsd-3-clause
- Created: 2020-07-14T18:35:15.000Z (almost 5 years ago)
- Default Branch: main
- Last Pushed: 2024-04-04T09:48:58.000Z (about 1 year ago)
- Last Synced: 2025-03-24T04:50:53.492Z (about 1 month ago)
- Topics: catch, color-output, dart, error-handling, exception, exception-handling, flutter, generics, parameterized, throw
- Language: Dart
- Homepage: https://pub.dev/packages/exception_templates
- Size: 137 KB
- Stars: 4
- Watchers: 0
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# Exception Templates
[](https://github.com/simphotonics/exception_templates/actions/workflows/dart.yml)
## Introduction
While it is possible to throw any object in Dart, production code typically contains
custom error and exception classes that
extend [`Error`][Error] and implement [`Exception`][Exception].An alternative approach consists in using exceptions with parameterized type.
The library [`exception_templates`][exception_templates] provides
parameterized classes that allow throwing errors/exceptions and filtering caught exceptions characterized
by their **type argument**.In the following sections the term *exception* stands for exception/error
with the understanding that in general exceptions should be handled while errors should lead to the
termination of the program.## Usage
To use this library include [exception_templates] as dependency in your `pubspec.yaml` file.### Highlighting the Exception Context
To highlight the **context** in which the exception/error occured use the classes
[`ExceptionOf`][ExceptionOf] and [`ErrorOf`][ErrorOf].
Hereby, the type argument indicates that the exception occured within a method of the class `T`.
In this case, there is no need to define class specific exceptions. See example below.```Dart
// To run this program navigate to the root of your local copy of the
// package exception_templates and use
//
// # dart example/bin/exception_example.dart
//
// followed by enter.
import 'package:exception_templates/exception_templates.dart';/// Returns the variable t afer some time. Used to simulate a database or
/// network connection.
Future later(T t) async {
return await Future.delayed(Duration(milliseconds: 200), () => t);
}/// Sample class
class UserForm {
const UserForm(this.userName);final String userName;
/// Simulates fetching user feedback from a database or network connection.
Future fetchFeedback() async {
final feedback = await later('');
if (feedback.isEmpty) {
throw ExceptionOf(
message: 'Could not process $userName\'s feedback.',
invalidState: 'String found: $feedback',
expectedState: 'A non-empty String.',
);
}
return feedback;
}
}void main(List args) async {
final userForm = UserForm('Daniel');
try {
final userFeedback = await userForm.fetchFeedback();
print(userFeedback);
} on ExceptionOf catch (e) {
final userFeedback = e.message;
print('Feedback: $userFeedback\n');
}
}
```### Highlighting the Exception Type
To emphasise the exception **type** use:
* [`ExceptionOfType`][ExceptionOfType], where `T extends ExceptionType`,
* [`ErrorOfType`][ErrorOfType] where `T extends ErrorType`.The program below demonstrates how
to throw an error of type `ErrorOfType`.```Dart
// To run this program navigate to the root of your local copy of the
// package exception_templates and use
//
// # dart example/bin/error_example.dart
//
// followed by enter.
import 'package:exception_templates/exception_templates.dart';// Defining error types:
class LengthMismatch extends ErrorType {}extension Subtraction on List {
/// Subtracts two numerical lists of same length.
List operator -(List other) {
if (length != other.length) {
throw ErrorOfType(
message: 'Could not calculate: $this - $other.',
invalidState: 'Length of $this does not match length of $other.',
expectedState: 'Two operands with the same length.');
}
return List.generate(length, (i) => this[i] - other[i]);
}
}void main(List args) {
final a = [1, 2];
final b = [3, 4];
final c = [...b, 5];
print('b - a = ${b - a}');
print('c - b = ${c - b}');
}```
A typical output produced when running the program above is displayed below (the stack trace is not shown):
Note: Colour output can be globally enabled or disabled by setting
the static variable `colorOutput`
to `ColorOutput.on` or `ColorOutput.off`, respectively:
```Dart
import 'package:exception_templates/exception_templates.dart';/// Turning off color output, e.g. if the terminal does not support it.
void main(List args) {
ErrorOfType.colorOutput = ColorOutput.off;
ExceptionOfType.colorOutput = ColorOutput.off;
}
```## Utility Functions
The library includes the utility functions [`validateIdentifier`][validateIdentifier] and [`isValidIdentifier`][isValidIdentifier].
The function [`validateIdentifier`][validateIdentifier] throws an error of
type `ErrorOfType`
if the String argument is a Dart keyword or an invalid Dart variable or function name.## Examples
A copy of the programs shown in the section above can be found in the folder [example].
## Features and bugs
Please file feature requests and bugs at the [issue tracker].
[issue tracker]: https://github.com/simphotonics/exception_templates/issues
[example]: example
[Error]: https://api.dart.dev/stable/dart-core/Error-class.html
[Exception]: https://api.dart.dev/stable/dart-core/Exception-class.html
[ExceptionOf]: https://pub.dev/documentation/exception_templates/latest/exception_templates/ExceptionOf-class.html
[ExceptionOfType]: https://pub.dev/documentation/exception_templates/latest/exception_templates/ExceptionOfType-class.html
[ErrorOf]: https://pub.dev/documentation/exception_templates/latest/exception_templates/ErrorOf-class.html
[ErrorOfType]: https://pub.dev/documentation/exception_templates/latest/exception_templates/ErrorOfType-class.html
[exception_templates]: https://pub.dev/packages/exception_templates
[isValidIdentifier]: https://pub.dev/documentation/exception_templates/latest/exception_templates/isValidIdentifier.html
[validateIdentifier]: https://pub.dev/documentation/exception_templates/latest/exception_templates/validateIdentifier.html