项目作者: simphotonics

项目描述 :
Parameterized exception and error classes for Dart. Enables throwing specific error objects without the need to define exception classes.
高级语言: Dart
项目地址: git://github.com/simphotonics/exception_templates.git
创建时间: 2020-07-14T18:35:15Z
项目社区:https://github.com/simphotonics/exception_templates

开源协议:BSD 3-Clause "New" or "Revised" License

下载


Exception Templates

Dart

Introduction

While it is possible to throw any object in Dart, production code typically contains
custom error and exception classes that
extend Error and implement Exception.

An alternative approach consists in using exceptions with parameterized type.
The library 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<T> and ErrorOf<T>.
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.

  1. // To run this program navigate to the root of your local copy of the
  2. // package exception_templates and use
  3. //
  4. // # dart example/bin/exception_example.dart
  5. //
  6. // followed by enter.
  7. import 'package:exception_templates/exception_templates.dart';
  8. /// Returns the variable t afer some time. Used to simulate a database or
  9. /// network connection.
  10. Future<T> later<T>(T t) async {
  11. return await Future.delayed(Duration(milliseconds: 200), () => t);
  12. }
  13. /// Sample class
  14. class UserForm {
  15. const UserForm(this.userName);
  16. final String userName;
  17. /// Simulates fetching user feedback from a database or network connection.
  18. Future<String> fetchFeedback() async {
  19. final feedback = await later('');
  20. if (feedback.isEmpty) {
  21. throw ExceptionOf<UserForm>(
  22. message: 'Could not process $userName\'s feedback.',
  23. invalidState: 'String found: $feedback',
  24. expectedState: 'A non-empty String.',
  25. );
  26. }
  27. return feedback;
  28. }
  29. }
  30. void main(List<String> args) async {
  31. final userForm = UserForm('Daniel');
  32. try {
  33. final userFeedback = await userForm.fetchFeedback();
  34. print(userFeedback);
  35. } on ExceptionOf<UserForm> catch (e) {
  36. final userFeedback = e.message;
  37. print('Feedback: $userFeedback\n');
  38. }
  39. }

Highlighting the Exception Type

To emphasise the exception type use:

The program below demonstrates how
to throw an error of type ErrorOfType<LengthMismatch>.

  1. // To run this program navigate to the root of your local copy of the
  2. // package exception_templates and use
  3. //
  4. // # dart example/bin/error_example.dart
  5. //
  6. // followed by enter.
  7. import 'package:exception_templates/exception_templates.dart';
  8. // Defining error types:
  9. class LengthMismatch extends ErrorType {}
  10. extension Subtraction on List<num> {
  11. /// Subtracts two numerical lists of same length.
  12. List<num> operator -(List<num> other) {
  13. if (length != other.length) {
  14. throw ErrorOfType<LengthMismatch>(
  15. message: 'Could not calculate: $this - $other.',
  16. invalidState: 'Length of $this does not match length of $other.',
  17. expectedState: 'Two operands with the same length.');
  18. }
  19. return List<num>.generate(length, (i) => this[i] - other[i]);
  20. }
  21. }
  22. void main(List<String> args) {
  23. final a = [1, 2];
  24. final b = [3, 4];
  25. final c = [...b, 5];
  26. print('b - a = ${b - a}');
  27. print('c - b = ${c - b}');
  28. }

A typical output produced when running the program above is displayed below (the stack trace is not shown):
Console Output

Note: Colour output can be globally enabled or disabled by setting
the static variable colorOutput
to ColorOutput.on or ColorOutput.off, respectively:

  1. import 'package:exception_templates/exception_templates.dart';
  2. /// Turning off color output, e.g. if the terminal does not support it.
  3. void main(List<String> args) {
  4. ErrorOfType.colorOutput = ColorOutput.off;
  5. ExceptionOfType.colorOutput = ColorOutput.off;
  6. }

Utility Functions

The library includes the utility functions validateIdentifier and isValidIdentifier.

The function validateIdentifier throws an error of
type ErrorOfType<InvalidIdentifier>
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.