{"id":18521798,"url":"https://github.com/simphotonics/exception_templates","last_synced_at":"2025-04-09T09:33:25.106Z","repository":{"id":54137748,"uuid":"279664501","full_name":"simphotonics/exception_templates","owner":"simphotonics","description":"Dart exception and error classes with generic type. Enables throwing and catching exceptions based on their type argument.","archived":false,"fork":false,"pushed_at":"2024-04-04T09:48:58.000Z","size":140,"stargazers_count":4,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-03-24T04:50:53.492Z","etag":null,"topics":["catch","color-output","dart","error-handling","exception","exception-handling","flutter","generics","parameterized","throw"],"latest_commit_sha":null,"homepage":"https://pub.dev/packages/exception_templates","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/simphotonics.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-07-14T18:35:15.000Z","updated_at":"2024-04-03T22:40:52.000Z","dependencies_parsed_at":"2024-11-06T17:35:42.332Z","dependency_job_id":"481b42f4-6c50-44bd-a857-c6b0385098d4","html_url":"https://github.com/simphotonics/exception_templates","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fexception_templates","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fexception_templates/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fexception_templates/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fexception_templates/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/simphotonics","download_url":"https://codeload.github.com/simphotonics/exception_templates/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248012864,"owners_count":21033254,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["catch","color-output","dart","error-handling","exception","exception-handling","flutter","generics","parameterized","throw"],"created_at":"2024-11-06T17:27:40.070Z","updated_at":"2025-04-09T09:33:24.583Z","avatar_url":"https://github.com/simphotonics.png","language":"Dart","readme":"# Exception Templates\n\n[![Dart](https://github.com/simphotonics/exception_templates/actions/workflows/dart.yml/badge.svg)](https://github.com/simphotonics/exception_templates/actions/workflows/dart.yml)\n\n\n## Introduction\n\nWhile it is possible to throw any object in Dart, production code typically contains\ncustom error and exception classes that\nextend [`Error`][Error] and implement [`Exception`][Exception].\n\nAn alternative approach consists in using exceptions with parameterized type.\nThe library [`exception_templates`][exception_templates] provides\nparameterized classes that allow throwing errors/exceptions and filtering caught exceptions characterized\nby their **type argument**.\n\nIn the following sections the term *exception* stands for exception/error\nwith the understanding that in general exceptions should be handled while errors should lead to the\ntermination of the program.\n\n\n\n## Usage\nTo use this library include [exception_templates] as dependency in your `pubspec.yaml` file.\n\n### Highlighting the Exception Context\nTo highlight the **context** in which the exception/error occured use the classes\n[`ExceptionOf\u003cT\u003e`][ExceptionOf\u003cT\u003e] and [`ErrorOf\u003cT\u003e`][ErrorOf\u003cT\u003e].\nHereby, the type argument indicates that the exception occured within a method of the class `T`.\nIn this case, there is no need to define class specific exceptions. See example below.\n\n```Dart\n// To run this program navigate to the root of your local copy of the\n// package exception_templates and use\n//\n// # dart example/bin/exception_example.dart\n//\n// followed by enter.\nimport 'package:exception_templates/exception_templates.dart';\n\n/// Returns the variable t afer some time. Used to simulate a database or\n/// network connection.\nFuture\u003cT\u003e later\u003cT\u003e(T t) async {\n  return await Future.delayed(Duration(milliseconds: 200), () =\u003e t);\n}\n\n/// Sample class\nclass UserForm {\n  const UserForm(this.userName);\n\n  final String userName;\n\n  /// Simulates fetching user feedback from a database or network connection.\n  Future\u003cString\u003e fetchFeedback() async {\n    final feedback = await later('');\n    if (feedback.isEmpty) {\n      throw ExceptionOf\u003cUserForm\u003e(\n        message: 'Could not process $userName\\'s feedback.',\n        invalidState: 'String found: $feedback',\n        expectedState: 'A non-empty String.',\n      );\n    }\n    return feedback;\n  }\n}\n\nvoid main(List\u003cString\u003e args) async {\n  final userForm = UserForm('Daniel');\n  try {\n    final userFeedback = await userForm.fetchFeedback();\n    print(userFeedback);\n  } on ExceptionOf\u003cUserForm\u003e catch (e) {\n    final userFeedback = e.message;\n    print('Feedback: $userFeedback\\n');\n  }\n}\n```\n\n### Highlighting the Exception Type\nTo emphasise the exception **type** use:\n* [`ExceptionOfType\u003cT\u003e`][ExceptionOfType\u003cT\u003e], where `T extends ExceptionType`,\n* [`ErrorOfType\u003cT\u003e`][ErrorOfType\u003cT\u003e] where `T extends ErrorType`.\n\nThe program below demonstrates how\nto throw an error of type `ErrorOfType\u003cLengthMismatch\u003e`.\n\n```Dart\n// To run this program navigate to the root of your local copy of the\n// package exception_templates and use\n//\n// # dart example/bin/error_example.dart\n//\n// followed by enter.\nimport 'package:exception_templates/exception_templates.dart';\n\n// Defining error types:\nclass LengthMismatch extends ErrorType {}\n\nextension Subtraction on List\u003cnum\u003e {\n  /// Subtracts two numerical lists of same length.\n  List\u003cnum\u003e operator -(List\u003cnum\u003e other) {\n    if (length != other.length) {\n      throw ErrorOfType\u003cLengthMismatch\u003e(\n          message: 'Could not calculate: $this - $other.',\n          invalidState: 'Length of $this does not match length of $other.',\n          expectedState: 'Two operands with the same length.');\n    }\n    return List\u003cnum\u003e.generate(length, (i) =\u003e this[i] - other[i]);\n  }\n}\n\nvoid main(List\u003cString\u003e args) {\n  final a = [1, 2];\n  final b = [3, 4];\n  final c = [...b, 5];\n  print('b - a = ${b - a}');\n  print('c - b = ${c - b}');\n}\n\n```\nA typical output produced when running the program above is displayed below (the stack trace is not shown):\n![Console Output](https://github.com/simphotonics/exception_templates/raw/main/images/console_output.svg?sanitize=true)\n\n\nNote: Colour output can be globally enabled or disabled by setting\nthe static variable `colorOutput`\nto `ColorOutput.on` or `ColorOutput.off`, respectively:\n```Dart\nimport 'package:exception_templates/exception_templates.dart';\n\n/// Turning off color output, e.g. if the terminal does not support it.\nvoid main(List\u003cString\u003e args) {\n  ErrorOfType.colorOutput = ColorOutput.off;\n  ExceptionOfType.colorOutput = ColorOutput.off;\n}\n```\n\n\n## Utility Functions\n\nThe library includes the utility functions [`validateIdentifier`][validateIdentifier] and [`isValidIdentifier`][isValidIdentifier].\n\nThe function [`validateIdentifier`][validateIdentifier] throws an error of\ntype `ErrorOfType\u003cInvalidIdentifier\u003e`\nif the String argument is a Dart keyword or an invalid Dart variable or function name.\n\n## Examples\n\nA copy of the programs shown in the section above can be found in the folder  [example].\n\n\n## Features and bugs\n\nPlease file feature requests and bugs at the [issue tracker].\n\n[issue tracker]: https://github.com/simphotonics/exception_templates/issues\n\n[example]: example\n\n[Error]: https://api.dart.dev/stable/dart-core/Error-class.html\n\n[Exception]: https://api.dart.dev/stable/dart-core/Exception-class.html\n\n[ExceptionOf\u003cT\u003e]: https://pub.dev/documentation/exception_templates/latest/exception_templates/ExceptionOf-class.html\n\n[ExceptionOfType\u003cT\u003e]: https://pub.dev/documentation/exception_templates/latest/exception_templates/ExceptionOfType-class.html\n\n[ErrorOf\u003cT\u003e]: https://pub.dev/documentation/exception_templates/latest/exception_templates/ErrorOf-class.html\n\n[ErrorOfType\u003cT\u003e]: https://pub.dev/documentation/exception_templates/latest/exception_templates/ErrorOfType-class.html\n\n[exception_templates]: https://pub.dev/packages/exception_templates\n\n[isValidIdentifier]: https://pub.dev/documentation/exception_templates/latest/exception_templates/isValidIdentifier.html\n\n[validateIdentifier]: https://pub.dev/documentation/exception_templates/latest/exception_templates/validateIdentifier.html\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsimphotonics%2Fexception_templates","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsimphotonics%2Fexception_templates","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsimphotonics%2Fexception_templates/lists"}