{"id":18319420,"url":"https://github.com/kariricode-framework/kariricode-exception","last_synced_at":"2026-01-27T23:10:14.472Z","repository":{"id":257932920,"uuid":"873705227","full_name":"KaririCode-Framework/kariricode-exception","owner":"KaririCode-Framework","description":"KaririCode Exception provides a robust and modular exception handling system for the KaririCode Framework, enabling seamless error management across various application domains.","archived":false,"fork":false,"pushed_at":"2024-10-17T22:44:01.000Z","size":110,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2024-10-20T09:14:33.804Z","etag":null,"topics":["error-management","exception-handling","framework","framework-php","kariri-code","modular-exceptions","php-exceptions","php-framework"],"latest_commit_sha":null,"homepage":"https://kariricode.org","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/KaririCode-Framework.png","metadata":{"files":{"readme":"README.md","changelog":null,"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":"2024-10-16T15:23:03.000Z","updated_at":"2024-10-17T22:43:37.000Z","dependencies_parsed_at":"2024-10-20T04:34:26.309Z","dependency_job_id":null,"html_url":"https://github.com/KaririCode-Framework/kariricode-exception","commit_stats":null,"previous_names":["kariricode-framework/kariricode-exception"],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KaririCode-Framework%2Fkariricode-exception","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KaririCode-Framework%2Fkariricode-exception/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KaririCode-Framework%2Fkariricode-exception/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KaririCode-Framework%2Fkariricode-exception/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/KaririCode-Framework","download_url":"https://codeload.github.com/KaririCode-Framework/kariricode-exception/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247406076,"owners_count":20933803,"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":["error-management","exception-handling","framework","framework-php","kariri-code","modular-exceptions","php-exceptions","php-framework"],"created_at":"2024-11-05T18:13:18.474Z","updated_at":"2026-01-27T23:10:14.419Z","avatar_url":"https://github.com/KaririCode-Framework.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# KaririCode Framework: Exception Component\n\n[![en](https://img.shields.io/badge/lang-en-red.svg)](README.md) [![pt-br](https://img.shields.io/badge/lang-pt--br-green.svg)](README.pt-br.md)\n\n![PHP](https://img.shields.io/badge/PHP-777BB4?style=for-the-badge\u0026logo=php\u0026logoColor=white) ![Docker](https://img.shields.io/badge/Docker-2496ED?style=for-the-badge\u0026logo=docker\u0026logoColor=white) ![PHPUnit](https://img.shields.io/badge/PHPUnit-3776AB?style=for-the-badge\u0026logo=php\u0026logoColor=white)\n\nA comprehensive and flexible exception handling component for PHP, part of the KaririCode Framework. It provides a structured approach to error management, enhancing the robustness and maintainability of your applications.\n\n## Table of Contents\n\n- [Features](#features)\n- [Installation](#installation)\n- [Usage](#usage)\n  - [Basic Usage](#basic-usage)\n  - [Advanced Usage](#advanced-usage)\n- [Error Code Range Table](#error-code-range-table)\n- [Available Exception Types](#available-exception-types)\n- [Integration with Other KaririCode Components](#integration-with-other-kariricode-components)\n- [Development and Testing](#development-and-testing)\n- [License](#license)\n- [Support and Community](#support-and-community)\n\n## Features\n\n- Hierarchical exception structure for better error categorization\n- Context-aware exceptions for richer error information\n- Static factory methods for easy exception creation\n- Integration with KaririCode's error handling and logging systems\n- Extensible architecture allowing custom exception types\n- Comprehensive set of pre-defined exception types for common scenarios\n\n## Installation\n\nYou can install the Exception component via Composer:\n\n```bash\ncomposer require kariricode/exception\n```\n\n### Requirements\n\n- PHP 8.1 or higher\n- Composer\n\n## Usage\n\n### Basic Usage\n\n#### Using Pre-defined Exceptions in Your Code\n\nThe KaririCode Exception component provides a variety of pre-defined exceptions that you can use to handle common error scenarios in a professional and structured manner. Below is an example of how to use these exceptions in an object-oriented context.\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nnamespace YourApp\\Controller;\n\nuse YourApp\\Service\\UserService;\nuse KaririCode\\Contract\\Http\\Response;\nuse KaririCode\\Contract\\Http\\ServerRequest;\nuse KaririCode\\Router\\Attributes\\Route;\n\nfinal class UserController extends BaseController\n{\n    public function __construct(private UserService $userService)\n    {\n    }\n\n    #[Route('/user/{userId}', methods: ['GET'])]\n    public function getUserData(ServerRequest $request, Response $response): Response\n    {\n        $userId = (int)$request-\u003egetAttribute('userId');\n\n        try {\n            $userData = $this-\u003euserService-\u003egetUserData($userId);\n            return $this-\u003eresponseBuilder($response)\n                -\u003esetData($userData)\n                -\u003esetHeader('Content-Type', 'application/json')\n                -\u003esetStatus(200)\n                -\u003ebuild();\n        } catch (\\Exception $e) {\n            // Handle exceptions and return appropriate error response\n            return $this-\u003eerrorResponse($response, $e);\n        }\n    }\n}\n\n// UserService.php\nnamespace YourApp\\Service;\n\nuse YourApp\\Repository\\UserRepository;\nuse KaririCode\\Contract\\Log\\Logger;\nuse KaririCode\\Exception\\Database\\DatabaseException;\n\nclass UserService\n{\n    public function __construct(\n        private UserRepository $userRepository,\n        private Logger $logger\n    ) {\n    }\n\n    /**\n     * @throws DatabaseException\n     */\n    public function getUserData(int $userId): array\n    {\n        try {\n            return $this-\u003euserRepository-\u003efindUserById($userId);\n        } catch (DatabaseException $e) {\n            $this-\u003elogger-\u003eerror('Failed to retrieve user data', [\n                'userId' =\u003e $userId,\n                'error' =\u003e $e-\u003egetMessage(),\n            ]);\n            throw $e;\n        }\n    }\n}\n\n// UserRepository.php\nnamespace YourApp\\Repository;\n\nuse KaririCode\\Contract\\Database\\EntityManager;\nuse KaririCode\\Exception\\Database\\DatabaseException;\n\nclass UserRepository\n{\n    public function __construct(private EntityManager $entityManager)\n    {\n    }\n\n    /**\n     * @throws DatabaseException\n     */\n    public function findUserById(int $userId): array\n    {\n        $sql = 'SELECT * FROM users WHERE id = ?';\n        try {\n            $userData = $this-\u003eentityManager-\u003equery($sql, [$userId]);\n\n            if (empty($userData)) {\n                throw DatabaseException::recordNotFound('User', $userId);\n            }\n\n            return $userData;\n        } catch (\\Exception $e) {\n            throw DatabaseException::queryError($sql, $e-\u003egetMessage());\n        }\n    }\n}\n```\n\n### Advanced Usage\n\nCreate custom exceptions by extending the base classes:\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nnamespace YourApp\\Exception;\n\nuse KaririCode\\Exception\\AbstractException;\n\nfinal class OrderException extends AbstractException\n{\n    private const CODE_ORDER_LIMIT_EXCEEDED = 4001;\n\n    public static function orderLimitExceeded(float $totalAmount, float $userOrderLimit): self\n    {\n        return self::createException(\n            self::CODE_ORDER_LIMIT_EXCEEDED,\n            'ORDER_LIMIT_EXCEEDED',\n            \"Order amount (${totalAmount}) exceeds user limit (${userOrderLimit})\"\n        );\n    }\n}\n```\n\nUsing custom exceptions in your application:\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nnamespace YourApp\\Service;\n\nuse YourApp\\Exception\\OrderException;\nuse YourApp\\Repository\\OrderRepository;\nuse KaririCode\\Contract\\Log\\Logger;\nuse KaririCode\\Exception\\Database\\DatabaseException;\n\nfinal class OrderService\n{\n    public function __construct(\n        private OrderRepository $orderRepository,\n        private Logger $logger\n    ) {\n    }\n\n    /**\n     * @throws OrderException\n     * @throws DatabaseException\n     */\n    public function placeOrder(int $userId, array $items, float $totalAmount): void\n    {\n        try {\n            $userOrderLimit = $this-\u003eorderRepository-\u003egetUserOrderLimit($userId);\n\n            if ($totalAmount \u003e $userOrderLimit) {\n                $this-\u003elogger-\u003ewarning('Order exceeds user limit', [\n                    'userId' =\u003e $userId,\n                    'orderAmount' =\u003e $totalAmount,\n                    'userLimit' =\u003e $userOrderLimit,\n                ]);\n\n                throw OrderException::orderLimitExceeded($totalAmount, $userOrderLimit);\n            }\n\n            $this-\u003eorderRepository-\u003ecreateOrder($userId, $items, $totalAmount);\n        } catch (DatabaseException $e) {\n            $this-\u003elogger-\u003eerror('Database error while placing order', [\n                'userId' =\u003e $userId,\n                'error' =\u003e $e-\u003egetMessage(),\n            ]);\n            throw $e;\n        }\n    }\n}\n```\n\n## Error Code Range Table\n\nHere is a proposed table for the **error code ranges**. Each range is assigned to a group of related errors, allowing better organization and identification of errors in the system.\n\n### Error Code Range Table\n\n| Range           | Error Group                 | Description                                           |\n| --------------- | --------------------------- | ----------------------------------------------------- |\n| **1000 - 1099** | **Authentication Errors**   | Errors related to authentication and login            |\n| **1100 - 1199** | **Authorization Errors**    | Errors related to permissions and roles               |\n| **1200 - 1299** | **Cache Errors**            | Errors related to cache operations                    |\n| **1300 - 1399** | **Configuration Errors**    | Errors related to configuration settings              |\n| **1400 - 1499** | **Container Errors**        | Errors related to dependency injection and services   |\n| **1500 - 1599** | **Database Errors**         | Errors related to database connections, queries, etc. |\n| **1600 - 1699** | **Event Errors**            | Errors related to event handling and dispatching      |\n| **1700 - 1799** | **External Service Errors** | Errors related to external API calls and services     |\n| **1800 - 1899** | **File System Errors**      | Errors related to file operations (reading, writing)  |\n| **1900 - 1999** | **Input/Validation Errors** | Errors related to invalid input or validation         |\n| **2000 - 2099** | **Localization Errors**     | Errors related to localization and translations       |\n| **2100 - 2199** | **Middleware Errors**       | Errors related to middleware processing               |\n| **2200 - 2299** | **Network Errors**          | Errors related to network operations                  |\n| **2300 - 2399** | **Queue Errors**            | Errors related to queuing systems                     |\n| **2400 - 2499** | **Routing Errors**          | Errors related to routing and HTTP methods            |\n| **2500 - 2599** | **Runtime Errors**          | General runtime errors                                |\n| **2600 - 2699** | **Encryption Errors**       | Errors related to encryption and decryption           |\n| **2700 - 2799** | **Security Errors**         | Errors related to security, access control, etc.      |\n| **2800 - 2899** | **Session Errors**          | Errors related to session handling                    |\n| **2900 - 2999** | **System Errors**           | Errors related to system resources and environment    |\n| **3000 - 3099** | **Template Errors**         | Errors related to template rendering and loading      |\n| **3100 - 3199** | **Validation Errors**       | Errors related to data validation                     |\n| **4000 - 4099** | **Business Logic Errors**   | Custom errors for business logic violations           |\n\n### Explanation of Each Range:\n\n1. **1000 - 1099: Authentication Errors**\n\n   - Errors related to user authentication, such as invalid credentials, locked accounts, or missing two-factor authentication.\n\n2. **1100 - 1199: Authorization Errors**\n\n   - Errors related to insufficient permissions or missing roles during authorization processes.\n\n3. **... (Same as previous ranges)**\n\n4. **3100 - 3199: Validation Errors**\n\n   - Errors related to data validation.\n\n5. **4000 - 4099: Business Logic Errors**\n   - Custom error codes for business logic violations specific to your application.\n\nThis structure allows you to easily categorize and expand error codes in the future, keeping the error-handling system organized.\n\n## Available Exception Types\n\nEach exception type is designed to handle specific error scenarios. For detailed information on each exception type, please refer to the [documentation](https://kariricode.org/docs/exception).\n\n## Integration with Other KaririCode Components\n\nThe Exception component is designed to work seamlessly with other KaririCode components:\n\n- **KaririCode\\Logger**: For advanced error logging and reporting.\n- **KaririCode\\Http**: For handling HTTP-related exceptions.\n- **KaririCode\\Database**: For database-specific exceptions.\n\n## Development and Testing\n\nFor development and testing purposes, this package uses Docker and Docker Compose to ensure consistency across different environments. A Makefile is provided for convenience.\n\n### Prerequisites\n\n- Docker\n- Docker Compose\n- Make (optional, but recommended for easier command execution)\n\n### Development Setup\n\n1. Clone the repository:\n\n   ```bash\n   git clone https://github.com/KaririCode-Framework/kariricode-exception.git\n   cd kariricode-exception\n   ```\n\n2. Set up the environment:\n\n   ```bash\n   make setup-env\n   ```\n\n3. Start the Docker containers:\n\n   ```bash\n   make up\n   ```\n\n4. Install dependencies:\n\n   ```bash\n   make composer-install\n   ```\n\n### Available Make Commands\n\n- `make up`: Start all services in the background\n- `make down`: Stop and remove all containers\n- `make build`: Build Docker images\n- `make shell`: Access the PHP container shell\n- `make test`: Run tests\n- `make coverage`: Run test coverage with visual formatting\n- `make cs-fix`: Run PHP CS Fixer to fix code style\n- `make quality`: Run all quality commands (cs-check, test, security-check)\n\nFor a full list of available commands, run:\n\n```bash\nmake help\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Support and Community\n\n- **Documentation**: [https://kariricode.org/docs/exception](https://kariricode.org/docs/exception)\n- **Issue Tracker**: [GitHub Issues](https://github.com/KaririCode-Framework/kariricode-exception/issues)\n- **Community**: [KaririCode Club Community](https://kariricode.club)\n\n---\n\nBuilt with ❤️ by the KaririCode team. Empowering developers to handle errors effectively and build more resilient PHP applications.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkariricode-framework%2Fkariricode-exception","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkariricode-framework%2Fkariricode-exception","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkariricode-framework%2Fkariricode-exception/lists"}