Skip to content

Commit ee11a4b

Browse files
committed
feat(docs): add README files in English and Portuguese for Exception component
- Added README.md (English version) with detailed instructions for using the Exception component - Added README.pt-br.md (Portuguese version) with equivalent content for Brazilian developers
1 parent 56a648d commit ee11a4b

File tree

4 files changed

+917
-89
lines changed

4 files changed

+917
-89
lines changed

README.md

Lines changed: 279 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,284 @@
1-
# KaririCode Framework: Sanitizer Component
1+
# KaririCode Framework: Exception Component
22

33
[![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)
44

55
![PHP](https://img.shields.io/badge/PHP-777BB4?style=for-the-badge&logo=php&logoColor=white) ![Docker](https://img.shields.io/badge/Docker-2496ED?style=for-the-badge&logo=docker&logoColor=white) ![PHPUnit](https://img.shields.io/badge/PHPUnit-3776AB?style=for-the-badge&logo=php&logoColor=white)
66

7+
A 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.
8+
9+
## Table of Contents
10+
11+
- [Features](#features)
12+
- [Installation](#installation)
13+
- [Usage](#usage)
14+
- [Basic Usage](#basic-usage)
15+
- [Advanced Usage](#advanced-usage)
16+
- [Error Code Range Table](#error-code-range-table)
17+
- [Available Exception Types](#available-exception-types)
18+
- [Integration with Other KaririCode Components](#integration-with-other-kariricode-components)
19+
- [Development and Testing](#development-and-testing)
20+
- [License](#license)
21+
- [Support and Community](#support-and-community)
22+
23+
## Features
24+
25+
- Hierarchical exception structure for better error categorization
26+
- Context-aware exceptions for richer error information
27+
- Static factory methods for easy exception creation
28+
- Integration with KaririCode's error handling and logging systems
29+
- Extensible architecture allowing custom exception types
30+
- Comprehensive set of pre-defined exception types for common scenarios
31+
32+
## Installation
33+
34+
You can install the Exception component via Composer:
35+
36+
```bash
37+
composer require kariricode/exception
38+
```
39+
40+
### Requirements
41+
42+
- PHP 8.1 or higher
43+
- Composer
44+
45+
## Usage
46+
47+
### Basic Usage
48+
49+
#### Using Pre-defined Exceptions in Your Code
50+
51+
The 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.
52+
53+
```php
54+
<?php
55+
56+
declare(strict_types=1);
57+
58+
namespace YourApp\Controller;
59+
60+
use YourApp\Service\UserService;
61+
use KaririCode\Contract\Http\Response;
62+
use KaririCode\Contract\Http\ServerRequest;
63+
use KaririCode\Router\Attributes\Route;
64+
65+
final class UserController extends BaseController
66+
{
67+
public function __construct(private UserService $userService)
68+
{
69+
}
70+
71+
#[Route('/user/{userId}', methods: ['GET'])]
72+
public function getUserData(ServerRequest $request, Response $response): Response
73+
{
74+
$userId = (int)$request->getAttribute('userId');
75+
76+
$userData = $this->userService->getUserData($userId);
77+
return $this->responseBuilder($response)
78+
->setData($userData)
79+
->setHeader('Content-Type', 'application/json')
80+
->setStatus(200)
81+
->build();
82+
}
83+
}
84+
85+
// UserService.php
86+
namespace YourApp\Service;
87+
88+
use YourApp\Repository\UserRepository;
89+
use KaririCode\Contract\Log\Logger;
90+
91+
class UserService
92+
{
93+
private UserRepository $userRepository;
94+
private Logger $logger;
95+
96+
public function __construct(UserRepository $userRepository, Logger $logger)
97+
{
98+
$this->userRepository = $userRepository;
99+
$this->logger = $logger;
100+
}
101+
102+
public function getUserData(int $userId): array
103+
{
104+
return $this->userRepository->findUserById($userId);
105+
}
106+
}
107+
108+
// UserRepository.php
109+
namespace YourApp\Repository;
110+
111+
use KaririCode\Contract\Database\EntityManager;
112+
use KaririCode\Exception\Database\DatabaseException;
113+
114+
class UserRepository
115+
{
116+
private EntityManager $entityManager;
117+
118+
public function __construct(EntityManager $entityManager)
119+
{
120+
$this->entityManager = $entityManager;
121+
}
122+
123+
public function findUserById(int $userId): array
124+
{
125+
$sql = 'SELECT * FROM users WHERE id = ?';
126+
$userData = $this->entityManager->query($sql, [$userId]);
127+
128+
if ($userData === false) {
129+
throw DatabaseException::queryError($sql, $this->entityManager->getLastError());
130+
}
131+
132+
return $userData;
133+
}
134+
}
135+
136+
```
137+
138+
### Advanced Usage
139+
140+
Create custom exceptions by extending the base classes:
141+
142+
```php
143+
<?php
144+
145+
declare(strict_types=1);
146+
147+
namespace YourApp\Exception;
148+
149+
use KaririCode\Exception\AbstractException;
150+
use KaririCode\Exception\ExceptionMessage;
151+
152+
final class OrderException extends AbstractException
153+
{
154+
private const CODE_ORDER_LIMIT_EXCEEDED = 4001;
155+
156+
public static function orderLimitExceeded(float $totalAmount, float $userOrderLimit): self
157+
{
158+
return new self(new ExceptionMessage(
159+
self::CODE_ORDER_LIMIT_EXCEEDED,
160+
'ORDER_LIMIT_EXCEEDED',
161+
"Order amount (${totalAmount}) exceeds user limit (${userOrderLimit})"
162+
));
163+
}
164+
}
165+
```
166+
167+
Using custom exceptions in your application:
168+
169+
```php
170+
<?php
171+
172+
declare(strict_types=1);
173+
174+
namespace YourApp\Service;
175+
176+
use YourApp\Exception\OrderException;
177+
use YourApp\Repository\OrderRepository;
178+
use KaririCode\Contract\Log\Logger;
179+
use KaririCode\Exception\Database\DatabaseException;
180+
181+
final class OrderService
182+
{
183+
public function __construct(
184+
private OrderRepository $orderRepository,
185+
private Logger $logger
186+
) {
187+
}
188+
189+
/**
190+
* @throws OrderException
191+
* @throws DatabaseException
192+
*/
193+
public function placeOrder(int $userId, array $items, float $totalAmount): void
194+
{
195+
$userOrderLimit = $this->orderRepository->getUserOrderLimit($userId);
196+
197+
if ($totalAmount > $userOrderLimit) {
198+
$this->logger->warning('Order exceeds user limit', [
199+
'userId' => $userId,
200+
'orderAmount' => $totalAmount,
201+
'userLimit' => $userOrderLimit,
202+
]);
203+
204+
throw OrderException::orderLimitExceeded($totalAmount, $userOrderLimit);
205+
}
206+
207+
$this->orderRepository->createOrder($userId, $items, $totalAmount);
208+
209+
}
210+
}
211+
```
212+
213+
## Error Code Range Table
214+
215+
Here 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.
216+
217+
### Error Code Range Table
218+
219+
| Range | Error Group | Description |
220+
| --------------- | --------------------------- | ----------------------------------------------------- |
221+
| **1000 - 1099** | **Authentication Errors** | Errors related to authentication and login |
222+
| **1100 - 1199** | **Authorization Errors** | Errors related to permissions and roles |
223+
| **1200 - 1299** | **Cache Errors** | Errors related to cache operations |
224+
| **1300 - 1399** | **Configuration Errors** | Errors related to configuration settings |
225+
| **1400 - 1499** | **Container Errors** | Errors related to dependency injection and services |
226+
| **1500 - 1599** | **Database Errors** | Errors related to database connections, queries, etc. |
227+
| **1600 - 1699** | **Event Errors** | Errors related to event handling and dispatching |
228+
| **1700 - 1799** | **External Service Errors** | Errors related to external API calls and services |
229+
| **1800 - 1899** | **File System Errors** | Errors related to file operations (reading, writing) |
230+
| **1900 - 1999** | **Input/Validation Errors** | Errors related to invalid input or validation |
231+
| **2000 - 2099** | **Localization Errors** | Errors related to localization and translations |
232+
| **2100 - 2199** | **Middleware Errors** | Errors related to middleware processing |
233+
| **2200 - 2299** | **Network Errors** | Errors related to network operations |
234+
| **2300 - 2399** | **Queue Errors** | Errors related to queuing systems |
235+
| **2400 - 2499** | **Routing Errors** | Errors related to routing and HTTP methods |
236+
| **2500 - 2599** | **Runtime Errors** | General runtime errors |
237+
| **2600 - 2699** | **Encryption Errors** | Errors related to encryption and decryption |
238+
| **2700 - 2799** | **Security Errors** | Errors related to security, access control, etc. |
239+
| **2800 - 2899** | **Session Errors** | Errors related to session handling |
240+
| **2900 - 2999** | **System Errors** | Errors related to system resources and environment |
241+
| **3000 - 3099** | **Template Errors** | Errors related to template rendering and loading |
242+
| **3100 - 3199** | **Validation Errors** | Errors related to data validation |
243+
| **4000 - 4099** | **Business Logic Errors** | Custom errors for business logic violations |
244+
245+
### Explanation of Each Range:
246+
247+
1. **1000 - 1099: Authentication Errors**
248+
249+
- Errors related to user authentication, such as invalid credentials, locked accounts, or missing two-factor authentication.
250+
251+
2. **1100 - 1199: Authorization Errors**
252+
253+
- Errors related to insufficient permissions or missing roles during authorization processes.
254+
255+
3. **... (Same as previous ranges)**
256+
257+
4. **3100 - 3199: Validation Errors**
258+
259+
- Errors related to data validation.
260+
261+
5. **4000 - 4099: Business Logic Errors**
262+
- Custom error codes for business logic violations specific to your application.
263+
264+
This structure allows you to easily categorize and expand error codes in the future, keeping the error-handling system organized.
265+
266+
## Available Exception Types
267+
268+
Each 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).
269+
270+
## Integration with Other KaririCode Components
271+
272+
The Exception component is designed to work seamlessly with other KaririCode components:
273+
274+
- **KaririCode\Logger**: For advanced error logging and reporting.
275+
- **KaririCode\Http**: For handling HTTP-related exceptions.
276+
- **KaririCode\Database**: For database-specific exceptions.
277+
278+
## Development and Testing
279+
280+
For development and testing purposes, this package uses Docker and Docker Compose to ensure consistency across different environments. A Makefile is provided for convenience.
281+
7282
### Prerequisites
8283

9284
- Docker
@@ -32,6 +307,7 @@
32307
```
33308

34309
4. Install dependencies:
310+
35311
```bash
36312
make composer-install
37313
```
@@ -59,10 +335,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
59335

60336
## Support and Community
61337

62-
- **Documentation**: [https://kariricode.org/docs/sanitizer](https://kariricode.org/docs/sanitizer)
338+
- **Documentation**: [https://kariricode.org/docs/exception](https://kariricode.org/docs/exception)
63339
- **Issue Tracker**: [GitHub Issues](https://github.com/KaririCode-Framework/kariricode-exception/issues)
64340
- **Community**: [KaririCode Club Community](https://kariricode.club)
65341

66342
---
67343

68-
Built with ❤️ by the KaririCode team. Empowering developers to create more secure and robust PHP applications.
344+
Built with ❤️ by the KaririCode team. Empowering developers to handle errors effectively and build more resilient PHP applications.

0 commit comments

Comments
 (0)