{"id":21677577,"url":"https://github.com/tech-andgar/exception_handler","last_synced_at":"2026-01-11T04:39:15.695Z","repository":{"id":214407818,"uuid":"736468669","full_name":"tech-andgar/exception_handler","owner":"tech-andgar","description":"A Dart package for streamlined API handling and robust exception management in Flutter apps.","archived":false,"fork":false,"pushed_at":"2025-01-20T03:32:49.000Z","size":1746,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-11T09:51:34.909Z","etag":null,"topics":["api","dart","dio","exception-handler","flutter"],"latest_commit_sha":null,"homepage":"https://pub.dev/packages/exception_handler","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tech-andgar.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}},"created_at":"2023-12-28T01:58:48.000Z","updated_at":"2024-08-01T21:51:53.000Z","dependencies_parsed_at":"2024-03-08T03:22:31.463Z","dependency_job_id":"6d12766e-7b4f-43da-abc0-e200a415e38e","html_url":"https://github.com/tech-andgar/exception_handler","commit_stats":null,"previous_names":["andgar2010/exception_handler","tech-andgar/exception_handler"],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tech-andgar%2Fexception_handler","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tech-andgar%2Fexception_handler/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tech-andgar%2Fexception_handler/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tech-andgar%2Fexception_handler/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tech-andgar","download_url":"https://codeload.github.com/tech-andgar/exception_handler/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244591364,"owners_count":20477707,"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":["api","dart","dio","exception-handler","flutter"],"created_at":"2024-11-25T14:20:50.062Z","updated_at":"2026-01-11T04:39:15.654Z","avatar_url":"https://github.com/tech-andgar.png","language":"Dart","readme":"# exception_handler\n\n| Local                             | Repo Git                                                                                                            | Coveralls                                                                                                                                                                        |\n| --------------------------------- | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| ![Coverage](./coverage_badge.svg) | ![Coverage](https://raw.githubusercontent.com/andgar2010/exception_handler/master/coverage_badge.svg?sanitize=true) | [![Coverage Status](https://coveralls.io/repos/github/andgar2010/exception_handler/badge.svg?branch=main)](https://coveralls.io/github/andgar2010/exception_handler?branch=main) |\n\nThis Dart package provides a robust framework for handling API calls and processing exceptions in Flutter applications.\nIt simplifies the process of making network requests, parsing responses, and handling various exceptions, making it an essential tool for Flutter developers.\n\n## Features\n\n- **API Handling:** Simplify your API calls with a structured approach, ensuring clean and maintainable code.\n- **Exception Management:** Comprehensive exception handling, including network issues and HTTP errors, to improve the robustness of your applications.\n\u003c!-- - **Connectivity Plus Integration:** Utilize the Connectivity Plus package for reliable network status checking. --\u003e\n\u003c!-- - **Custom Equatable Implementations:** Enhance the comparability of your objects with custom Equatable classes. --\u003e\n\n## Getting Started\n\nTo start using this package, add it as a dependency in your `pubspec.yaml` file:\n\n```yaml\ndependencies:\n  exception_handler: ^latest_version\n```\n\nThen, import it in your Dart files where you want to use it:\n\n```dartimport 'package:dio/dio.dart';\nimport 'package:exception_handler/exception_handler.dart';\n```\n\n## Usage\n\nThis package simplifies the process of making API calls and handling exceptions in Flutter apps.\nBelow are some examples to demonstrate how to use various features of the package.\n\n## Fetching and Enhanced Parsing of JSON Data with Dio and a Custom Extension\n\nIn our latest update, version 2.0.0, we have streamlined the process of fetching data from a REST API and converting it into a Dart object. This improvement utilizes Dio, a powerful HTTP client for Dart, enabling us to simplify our codebase while maintaining both efficiency and readability.\n\nHarness the power of Dio for handling HTTP requests in your Dart or Flutter applications, now further simplified with a custom `.fromJson()` extension method. This enhancement allows you to directly fetch data from your endpoints and convert them into Dart objects through one fluid operation, reducing boilerplate code and improving readability.\n\n### Defining a Model\n\nTo begin, create your data model with a factory constructor designed for JSON deserialization. Below is an example of a `UserModel`:\n\n```dart\nclass UserModel {\n  final int id;\n  final String name;\n  final String email;\n\n  UserModel({required this.id, required this.name, required this.email});\n\n  factory UserModel.fromJson(Map\u003cString, dynamic\u003e json) {\n    return UserModel(\n      id: json['id'],\n      name: json['name'],\n      email: json['email'],\n    );\n  }\n}\n```\n\nWith the custom extension in place, fetching data and parsing it into a Dart object becomes straightforward. Here's how to implement it in your application:\n\n```dart\nFuture\u003cvoid\u003e main() async {\n  Dio dio = Dio(); // Instantiate Dio\n  final int userId = 1; // Example user ID\n\n  final ResultState\u003cUserModel\u003e resultState = await dio\n      .get('https://jsonplaceholder.typicode.com/users/$userId')\n      .fromJson(UserModel.fromJson);\n\n  print(resultState.data); // Utilize the fetched and parsed userModel data\n  final Widget uiWidget = switch (resultState) {\n    SuccessState\u003cUserModel\u003e success =\u003e\n      UiUserWidget(success.data), // Using a hypothetical UiUserWidget for displaying user data\n    FailureState\u003cUserModel\u003e failure =\u003e\n      UiExceptionWidget(failure.exception), // Using a hypothetical UiExceptionWidget for handling errors\n  };\n```\n\n### Basic API Call\n\nHere's a simple example of making an API call and handling the response:\n\n```dart\nimport 'package:dio/dio.dart';\nimport 'package:exception_handler/exception_handler.dart';\n\n// Example of making an API call\nFuture\u003cvoid\u003e fetchUserData() async {\n    final ApiHandler\u003cResponse, UserModel\u003e apiHandler = ApiHandler(\n        apiCall: () =\u003e dio.get('https://example.com/api/user'),\n        parserModel: (data) =\u003e UserModel.fromJson(data),\n    );\n\n    // ResultState\u003cUserModel\u003e result = await DioExceptionHandler().callApi(apiHandler); // v1.x.x\n    ResultState\u003cUserModel\u003e result = await DioExceptionHandler.callApi_(apiHandler);\n\n    switch (result) {\n      case SuccessState\u003cUserModel\u003e(:UserModel data):\n        print('UserModel data: $data');\n      case FailureState\u003cUserModel\u003e(:ExceptionState exception):\n        print('Error: ${exception.toString()}');\n    }\n}\n```\n\nReplace `UserModel` with the appropriate data model for your application.\n\n### Advanced API Call with Custom Parser\n\nUsing a custom parser for complex API responses:\n\n```dart\nimport 'package:dio/dio.dart';\nimport 'package:exception_handler/exception_handler.dart';\n\nFuture\u003cvoid\u003e fetchComplexData() async {\n    final ApiHandler\u003cResponse, ComplexData\u003e apiHandler = ApiHandler(\n        apiCall: () =\u003e dio.get('https://example.com/api/complex'),\n        parserModel: customParser,\n    );\n\n    // ResultState\u003cComplexData\u003e result = await DioExceptionHandler().callApi(apiHandler); // v1.x.x\n    ResultState\u003cComplexData\u003e result = await DioExceptionHandler.callApi_(apiHandler);\n\n    switch (result) {\n      case SuccessState\u003cComplexData\u003e(:ComplexData data):\n        print('Complex Data: $data');\n      case FailureState\u003cComplexData\u003e(:ExceptionState exception):\n        print('Error: ${exception.toString()}');\n    }\n}\n\nComplexData customParser(dynamic responseData) {\n    // Custom parsing logic\n    return ComplexData.fromResponse(responseData);\n}\n```\n\n### Basic Exception Handling\n\nHandling basic exceptions with logging information:\n\n```dart\nvoid handleApiCall() async {\n    // ResultState\u003cUserModel\u003e result = await DioExceptionHandler().callApi(apiHandler); // v1.x.x\n    ResultState\u003cUserModel\u003e result = await DioExceptionHandler.callApi_(apiHandler);\n\n    switch (result) {\n      case SuccessState\u003cUserModel\u003e(:UserModel data):\n        print('User data retrieved successfully: $data');\n      case FailureState\u003cUserModel\u003e(:ExceptionState exception):\n        print('Exception occurred: ${exception.toString()}');\n        // Additional logging or error handling\n    }\n}\n```\n\n### Advanced Exception Handling with Specific Cases\n\nImplementing detailed handling for each type of exception:\n\n```dart\nvoid advancedExceptionHandling() async {\n    // ResultState\u003cUserModel\u003e result = await DioExceptionHandler().callApi(apiHandler); // v1.x.x\n    ResultState\u003cUserModel\u003e result = await DioExceptionHandler.callApi_(apiHandler);\n\n    switch (result) {\n      case SuccessState\u003cUserModel\u003e(:UserModel data):\n        print('Fetched data: $data');\n\n      case FailureState\u003cUserModel\u003e(:ExceptionState exception):\n        _handleExceptions(exception);\n    }\n\n}\n\nvoid _handleExceptions(ExceptionState exception) {\n  switch (exception) {\n    case DataClientExceptionState():\n      // Handle client-side exceptions\n      handleClientException(exception);\n    case DataParseExceptionState():\n      // Handle parsing-related exceptions\n      handleParseException(exception);\n    case DataHttpExceptionState():\n      // Handle HTTP-related exceptions\n      handleHttpException(exception);\n    case DataNetworkExceptionState():\n      // Handle network-related exceptions\n      handleNetworkException(exception);\n    case _:\n      // Handle any other types of exceptions\n      handleUnknownException(exception);\n  }\n}\n\nvoid handleNetworkException(DataNetworkExceptionState exception) {\n    print('Network Exception: ${exception.networkException}');\n    // Additional logic for handling network exceptions\n}\n\nvoid handleHttpException(DataHttpExceptionState exception) {\n    print('HTTP Exception: ${exception.httpException}');\n    // Additional logic for handling HTTP exceptions\n}\n\nvoid handleParseException(DataParseExceptionState exception) {\n    print('Parse Exception: ${exception.parseException}');\n    // Additional logic for handling parsing exceptions\n}\n\nvoid handleClientException(DataClientExceptionState exception) {\n    print('Client Exception: ${exception.clientException}');\n    // Additional logic for handling client-side exceptions\n}\n\nvoid handleUnknownException(ExceptionState exception) {\n    print('Unknown Exception: ${exception.toString()}');\n    // Additional logic for handling unknown exceptions\n}\n```\n\nIn these methods, you can add specific actions that should be taken when each type of exception occurs.\nFor example, you might show different error messages to the user, log the error for further analysis, or try alternative approaches if possible.\n\nThese examples provide a structured approach to handle different kinds of exceptions that might occur during API interactions in a Flutter app, ensuring that each case is dealt with appropriately.\n\n\u003c!-- For more detailed and complex usage examples, please refer to the `/example` folder in this package. --\u003e\n\n### Contribution and Support\n\nFor contributing to the package, refer to the `CONTRIBUTING.md` file in the package repository. If you encounter any issues or require support, please file an issue on the repository's issue tracker.\n\n## Additional Information\n\nFor more information on how to use this package, contribute to its development, or file issues, please visit [exception_handler](https://github.com/andgar2010/exception_handler). The package authors are committed to maintaining and improving this tool, and your feedback and contributions are greatly welcomed.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftech-andgar%2Fexception_handler","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftech-andgar%2Fexception_handler","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftech-andgar%2Fexception_handler/lists"}