diff --git a/README.md b/README.md index 21dac99..11103be 100644 --- a/README.md +++ b/README.md @@ -73,12 +73,17 @@ final class UserController extends BaseController { $userId = (int)$request->getAttribute('userId'); - $userData = $this->userService->getUserData($userId); - return $this->responseBuilder($response) - ->setData($userData) - ->setHeader('Content-Type', 'application/json') - ->setStatus(200) - ->build(); + try { + $userData = $this->userService->getUserData($userId); + return $this->responseBuilder($response) + ->setData($userData) + ->setHeader('Content-Type', 'application/json') + ->setStatus(200) + ->build(); + } catch (\Exception $e) { + // Handle exceptions and return appropriate error response + return $this->errorResponse($response, $e); + } } } @@ -87,21 +92,30 @@ namespace YourApp\Service; use YourApp\Repository\UserRepository; use KaririCode\Contract\Log\Logger; +use KaririCode\Exception\Database\DatabaseException; class UserService { - private UserRepository $userRepository; - private Logger $logger; - - public function __construct(UserRepository $userRepository, Logger $logger) - { - $this->userRepository = $userRepository; - $this->logger = $logger; + public function __construct( + private UserRepository $userRepository, + private Logger $logger + ) { } + /** + * @throws DatabaseException + */ public function getUserData(int $userId): array { - return $this->userRepository->findUserById($userId); + try { + return $this->userRepository->findUserById($userId); + } catch (DatabaseException $e) { + $this->logger->error('Failed to retrieve user data', [ + 'userId' => $userId, + 'error' => $e->getMessage(), + ]); + throw $e; + } } } @@ -113,26 +127,29 @@ use KaririCode\Exception\Database\DatabaseException; class UserRepository { - private EntityManager $entityManager; - - public function __construct(EntityManager $entityManager) + public function __construct(private EntityManager $entityManager) { - $this->entityManager = $entityManager; } + /** + * @throws DatabaseException + */ public function findUserById(int $userId): array { $sql = 'SELECT * FROM users WHERE id = ?'; - $userData = $this->entityManager->query($sql, [$userId]); + try { + $userData = $this->entityManager->query($sql, [$userId]); - if ($userData === false) { - throw DatabaseException::queryError($sql, $this->entityManager->getLastError()); - } + if (empty($userData)) { + throw DatabaseException::recordNotFound('User', $userId); + } - return $userData; + return $userData; + } catch (\Exception $e) { + throw DatabaseException::queryError($sql, $e->getMessage()); + } } } - ``` ### Advanced Usage @@ -147,7 +164,6 @@ declare(strict_types=1); namespace YourApp\Exception; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class OrderException extends AbstractException { @@ -155,11 +171,11 @@ final class OrderException extends AbstractException public static function orderLimitExceeded(float $totalAmount, float $userOrderLimit): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_ORDER_LIMIT_EXCEEDED, 'ORDER_LIMIT_EXCEEDED', "Order amount (${totalAmount}) exceeds user limit (${userOrderLimit})" - )); + ); } } ``` @@ -192,20 +208,27 @@ final class OrderService */ public function placeOrder(int $userId, array $items, float $totalAmount): void { - $userOrderLimit = $this->orderRepository->getUserOrderLimit($userId); - - if ($totalAmount > $userOrderLimit) { - $this->logger->warning('Order exceeds user limit', [ - 'userId' => $userId, - 'orderAmount' => $totalAmount, - 'userLimit' => $userOrderLimit, - ]); - - throw OrderException::orderLimitExceeded($totalAmount, $userOrderLimit); - } - - $this->orderRepository->createOrder($userId, $items, $totalAmount); - + try { + $userOrderLimit = $this->orderRepository->getUserOrderLimit($userId); + + if ($totalAmount > $userOrderLimit) { + $this->logger->warning('Order exceeds user limit', [ + 'userId' => $userId, + 'orderAmount' => $totalAmount, + 'userLimit' => $userOrderLimit, + ]); + + throw OrderException::orderLimitExceeded($totalAmount, $userOrderLimit); + } + + $this->orderRepository->createOrder($userId, $items, $totalAmount); + } catch (DatabaseException $e) { + $this->logger->error('Database error while placing order', [ + 'userId' => $userId, + 'error' => $e->getMessage(), + ]); + throw $e; + } } } ``` diff --git a/README.pt-br.md b/README.pt-br.md index f5bfd30..eab556e 100644 --- a/README.pt-br.md +++ b/README.pt-br.md @@ -46,9 +46,9 @@ composer require kariricode/exception ### Uso Básico -#### Usando Exceções Pré-definidas no Seu Código +#### Usando Exceções Pré-definidas em Seu Código -O componente KaririCode Exception oferece uma variedade de exceções pré-definidas que você pode usar para lidar com cenários comuns de erro de maneira profissional e estruturada. Abaixo está um exemplo de como usar essas exceções em um contexto orientado a objetos. +O componente de Exceção do KaririCode fornece uma variedade de exceções pré-definidas que você pode usar para lidar com cenários de erro comuns de maneira profissional e estruturada. Abaixo está um exemplo de como usar essas exceções em um contexto orientado a objetos. ```php getAttribute('userId'); - $userData = $this->userService->getUserData($userId); - return $this->responseBuilder($response) - ->setData($userData) - ->setHeader('Content-Type', 'application/json') - ->setStatus(200) - ->build(); + try { + $userData = $this->userService->getUserData($userId); + return $this->responseBuilder($response) + ->setData($userData) + ->setHeader('Content-Type', 'application/json') + ->setStatus(200) + ->build(); + } catch (\Exception $e) { + // Handle exceptions and return appropriate error response + return $this->errorResponse($response, $e); + } } } @@ -87,21 +92,30 @@ namespace YourApp\Service; use YourApp\Repository\UserRepository; use KaririCode\Contract\Log\Logger; +use KaririCode\Exception\Database\DatabaseException; class UserService { - private UserRepository $userRepository; - private Logger $logger; - - public function __construct(UserRepository $userRepository, Logger $logger) - { - $this->userRepository = $userRepository; - $this->logger = $logger; + public function __construct( + private UserRepository $userRepository, + private Logger $logger + ) { } + /** + * @throws DatabaseException + */ public function getUserData(int $userId): array { - return $this->userRepository->findUserById($userId); + try { + return $this->userRepository->findUserById($userId); + } catch (DatabaseException $e) { + $this->logger->error('Failed to retrieve user data', [ + 'userId' => $userId, + 'error' => $e->getMessage(), + ]); + throw $e; + } } } @@ -113,26 +127,29 @@ use KaririCode\Exception\Database\DatabaseException; class UserRepository { - private EntityManager $entityManager; - - public function __construct(EntityManager $entityManager) + public function __construct(private EntityManager $entityManager) { - $this->entityManager = $entityManager; } + /** + * @throws DatabaseException + */ public function findUserById(int $userId): array { $sql = 'SELECT * FROM users WHERE id = ?'; - $userData = $this->entityManager->query($sql, [$userId]); + try { + $userData = $this->entityManager->query($sql, [$userId]); - if ($userData === false) { - throw DatabaseException::queryError($sql, $this->entityManager->getLastError()); - } + if (empty($userData)) { + throw DatabaseException::recordNotFound('User', $userId); + } - return $userData; + return $userData; + } catch (\Exception $e) { + throw DatabaseException::queryError($sql, $e->getMessage()); + } } } - ``` ### Uso Avançado @@ -147,7 +164,6 @@ declare(strict_types=1); namespace YourApp\Exception; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class OrderException extends AbstractException { @@ -155,11 +171,11 @@ final class OrderException extends AbstractException public static function orderLimitExceeded(float $totalAmount, float $userOrderLimit): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_ORDER_LIMIT_EXCEEDED, 'ORDER_LIMIT_EXCEEDED', - "Valor do pedido (${totalAmount}) excede o limite do usuário (${userOrderLimit})" - )); + "Order amount (${totalAmount}) exceeds user limit (${userOrderLimit})" + ); } } ``` @@ -192,20 +208,27 @@ final class OrderService */ public function placeOrder(int $userId, array $items, float $totalAmount): void { - $userOrderLimit = $this->orderRepository->getUserOrderLimit($userId); - - if ($totalAmount > $userOrderLimit) { - $this->logger->warning('Pedido excede o limite do usuário', [ - 'userId' => $userId, - 'orderAmount' => $totalAmount, - 'userLimit' => $userOrderLimit, - ]); - - throw OrderException::orderLimitExceeded($totalAmount, $userOrderLimit); - } - - $this->orderRepository->createOrder($userId, $items, $totalAmount); - + try { + $userOrderLimit = $this->orderRepository->getUserOrderLimit($userId); + + if ($totalAmount > $userOrderLimit) { + $this->logger->warning('Order exceeds user limit', [ + 'userId' => $userId, + 'orderAmount' => $totalAmount, + 'userLimit' => $userOrderLimit, + ]); + + throw OrderException::orderLimitExceeded($totalAmount, $userOrderLimit); + } + + $this->orderRepository->createOrder($userId, $items, $totalAmount); + } catch (DatabaseException $e) { + $this->logger->error('Database error while placing order', [ + 'userId' => $userId, + 'error' => $e->getMessage(), + ]); + throw $e; + } } } ``` diff --git a/src/AbstractException.php b/src/AbstractException.php index 2a1de1f..e97d0ac 100644 --- a/src/AbstractException.php +++ b/src/AbstractException.php @@ -16,7 +16,6 @@ public function __construct(ErrorMessage $errorMessage, ?\Throwable $previous = { $this->errorCode = $errorMessage->getErrorCode(); $this->context = array_merge(['code' => $this->errorCode], $context); - parent::__construct($errorMessage->getMessage(), $errorMessage->getCode(), $previous); } @@ -36,4 +35,9 @@ protected function addContext(string $key, mixed $value): self return $this; } + + protected static function createException(int $code, string $errorCode, string $message): self + { + return new static(new ExceptionMessage($code, $errorCode, $message)); + } } diff --git a/src/Auth/AuthenticationException.php b/src/Auth/AuthenticationException.php index 33a2383..be826b0 100644 --- a/src/Auth/AuthenticationException.php +++ b/src/Auth/AuthenticationException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Auth; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class AuthenticationException extends AbstractException { @@ -15,28 +14,28 @@ final class AuthenticationException extends AbstractException public static function invalidCredentials(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_INVALID_CREDENTIALS, 'INVALID_CREDENTIALS', 'Invalid credentials provided' - )); + ); } public static function accountLocked(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_ACCOUNT_LOCKED, 'ACCOUNT_LOCKED', 'Account is locked' - )); + ); } public static function twoFactorRequired(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_TWO_FACTOR_REQUIRED, 'TWO_FACTOR_REQUIRED', 'Two-factor authentication is required' - )); + ); } } diff --git a/src/Auth/AuthorizationException.php b/src/Auth/AuthorizationException.php index db9255d..4bd0f1a 100644 --- a/src/Auth/AuthorizationException.php +++ b/src/Auth/AuthorizationException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Auth; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class AuthorizationException extends AbstractException { @@ -14,19 +13,19 @@ final class AuthorizationException extends AbstractException public static function insufficientPermissions(string $action): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_INSUFFICIENT_PERMISSIONS, 'INSUFFICIENT_PERMISSIONS', "Insufficient permissions for action: {$action}" - )); + ); } public static function roleRequired(string $role): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_ROLE_REQUIRED, 'ROLE_REQUIRED', "Required role not present: {$role}" - )); + ); } } diff --git a/src/Cache/CacheException.php b/src/Cache/CacheException.php index 0e20f30..b7fc3d5 100644 --- a/src/Cache/CacheException.php +++ b/src/Cache/CacheException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Cache; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class CacheException extends AbstractException { @@ -15,28 +14,28 @@ final class CacheException extends AbstractException public static function itemNotFound(string $key): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_ITEM_NOT_FOUND, 'CACHE_ITEM_NOT_FOUND', "Cache item not found: {$key}" - )); + ); } public static function storageError(string $details): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_STORAGE_ERROR, 'CACHE_STORAGE_ERROR', "Cache storage error: {$details}" - )); + ); } public static function invalidTtl(int $ttl): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_INVALID_TTL, 'INVALID_TTL', "Invalid TTL value: {$ttl}" - )); + ); } } diff --git a/src/Config/ConfigurationException.php b/src/Config/ConfigurationException.php index 10157dd..a40d396 100644 --- a/src/Config/ConfigurationException.php +++ b/src/Config/ConfigurationException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Config; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class ConfigurationException extends AbstractException { @@ -15,28 +14,28 @@ final class ConfigurationException extends AbstractException public static function missingKey(string $key): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_MISSING_KEY, 'MISSING_CONFIG_KEY', "Missing configuration key: {$key}" - )); + ); } public static function invalidValue(string $key, mixed $value): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_INVALID_VALUE, 'INVALID_CONFIG_VALUE', "Invalid configuration value for key '{$key}': " . var_export($value, true) - )); + ); } public static function environmentNotSet(string $envVar): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_ENVIRONMENT_NOT_SET, 'ENVIRONMENT_NOT_SET', "Environment variable not set: {$envVar}" - )); + ); } } diff --git a/src/Container/ContainerException.php b/src/Container/ContainerException.php index fa85dce..73ee9fd 100644 --- a/src/Container/ContainerException.php +++ b/src/Container/ContainerException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Container; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class ContainerException extends AbstractException { @@ -14,19 +13,19 @@ final class ContainerException extends AbstractException public static function serviceNotFound(string $serviceId): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_SERVICE_NOT_FOUND, 'SERVICE_NOT_FOUND', "Service not found in container: {$serviceId}" - )); + ); } public static function circularDependency(string $serviceId): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_CIRCULAR_DEPENDENCY, 'CIRCULAR_DEPENDENCY', "Circular dependency detected for service: {$serviceId}" - )); + ); } } diff --git a/src/Database/DatabaseException.php b/src/Database/DatabaseException.php index eeb6ed6..8689b30 100644 --- a/src/Database/DatabaseException.php +++ b/src/Database/DatabaseException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Database; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class DatabaseException extends AbstractException { @@ -15,28 +14,28 @@ final class DatabaseException extends AbstractException public static function connectionError(string $details): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_CONNECTION_ERROR, 'DB_CONNECTION_ERROR', "Database connection error: {$details}" - )); + ); } public static function queryError(string $query, string $error): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_QUERY_ERROR, 'DB_QUERY_ERROR', "Database query error: {$error}" - )); + ); } public static function deadlockDetected(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_DEADLOCK_DETECTED, 'DB_DEADLOCK', 'Database deadlock detected' - )); + ); } } diff --git a/src/Event/EventException.php b/src/Event/EventException.php index 544a968..10017a0 100644 --- a/src/Event/EventException.php +++ b/src/Event/EventException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Event; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class EventException extends AbstractException { @@ -14,19 +13,19 @@ final class EventException extends AbstractException public static function listenerNotCallable(string $eventName): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_LISTENER_NOT_CALLABLE, 'LISTENER_NOT_CALLABLE', "Event listener is not callable for event: {$eventName}" - )); + ); } public static function eventDispatchFailed(string $eventName): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_EVENT_DISPATCH_FAILED, 'EVENT_DISPATCH_FAILED', "Failed to dispatch event: {$eventName}" - )); + ); } } diff --git a/src/ExternalService/ExternalServiceException.php b/src/ExternalService/ExternalServiceException.php index c7d9bed..93548c7 100644 --- a/src/ExternalService/ExternalServiceException.php +++ b/src/ExternalService/ExternalServiceException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\ExternalService; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class ExternalServiceException extends AbstractException { @@ -15,28 +14,28 @@ final class ExternalServiceException extends AbstractException public static function apiError(string $service, string $error): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_API_ERROR, 'API_ERROR', "Error from external service '{$service}': {$error}" - )); + ); } public static function serviceUnavailable(string $service): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_SERVICE_UNAVAILABLE, 'SERVICE_UNAVAILABLE', "External service unavailable: {$service}" - )); + ); } public static function invalidResponse(string $service): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_INVALID_RESPONSE, 'INVALID_RESPONSE', "Invalid response from external service: {$service}" - )); + ); } } diff --git a/src/File/FileException.php b/src/File/FileException.php index 1e55627..2c4abf1 100644 --- a/src/File/FileException.php +++ b/src/File/FileException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\File; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class FileException extends AbstractException { @@ -16,37 +15,37 @@ final class FileException extends AbstractException public static function notFound(string $path): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_NOT_FOUND, 'FILE_NOT_FOUND', "File not found: {$path}" - )); + ); } public static function permissionDenied(string $path): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_PERMISSION_DENIED, 'PERMISSION_DENIED', "Permission denied for file: {$path}" - )); + ); } public static function unreadable(string $path): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_UNREADABLE, 'FILE_UNREADABLE', "File is not readable: {$path}" - )); + ); } public static function uploadFailed(string $filename): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_UPLOAD_FAILED, 'UPLOAD_FAILED', "Failed to upload file: {$filename}" - )); + ); } } diff --git a/src/Input/InputException.php b/src/Input/InputException.php index 2795c20..97b7d0e 100644 --- a/src/Input/InputException.php +++ b/src/Input/InputException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Input; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class InputException extends AbstractException { @@ -15,28 +14,28 @@ final class InputException extends AbstractException public static function invalidFormat(string $field): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_INVALID_FORMAT, 'INVALID_FORMAT', "Invalid format for field: {$field}" - )); + ); } public static function missingRequired(string $field): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_MISSING_REQUIRED, 'MISSING_REQUIRED', "Missing required field: {$field}" - )); + ); } public static function exceedsMaxLength(string $field, int $maxLength): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_EXCEEDS_MAX_LENGTH, 'EXCEEDS_MAX_LENGTH', "Field '{$field}' exceeds maximum length of {$maxLength}" - )); + ); } } diff --git a/src/Localization/LocalizationException.php b/src/Localization/LocalizationException.php index 560ab1e..e9e3959 100644 --- a/src/Localization/LocalizationException.php +++ b/src/Localization/LocalizationException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Localization; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class LocalizationException extends AbstractException { @@ -14,19 +13,19 @@ final class LocalizationException extends AbstractException public static function missingTranslation(string $key, string $locale): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_MISSING_TRANSLATION, 'MISSING_TRANSLATION', "Missing translation for key '{$key}' in locale '{$locale}'" - )); + ); } public static function invalidLocale(string $locale): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_INVALID_LOCALE, 'INVALID_LOCALE', "Invalid locale: {$locale}" - )); + ); } } diff --git a/src/Middleware/MiddlewareException.php b/src/Middleware/MiddlewareException.php index 3fed9d9..40ac0bd 100644 --- a/src/Middleware/MiddlewareException.php +++ b/src/Middleware/MiddlewareException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Middleware; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class MiddlewareException extends AbstractException { @@ -14,19 +13,19 @@ final class MiddlewareException extends AbstractException public static function invalidMiddleware(string $middlewareName): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_INVALID_MIDDLEWARE, 'INVALID_MIDDLEWARE', "Invalid middleware: {$middlewareName}" - )); + ); } public static function middlewareExecutionFailed(string $middlewareName): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_MIDDLEWARE_EXECUTION_FAILED, 'MIDDLEWARE_EXECUTION_FAILED', "Execution failed for middleware: {$middlewareName}" - )); + ); } } diff --git a/src/Network/HttpException.php b/src/Network/HttpException.php index 6a4de2c..ae29055 100644 --- a/src/Network/HttpException.php +++ b/src/Network/HttpException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Network; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class HttpException extends AbstractException { @@ -14,19 +13,19 @@ final class HttpException extends AbstractException public static function clientError(int $statusCode): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_CLIENT_ERROR, 'HTTP_CLIENT_ERROR', "HTTP client error with status code: {$statusCode}" - )); + ); } public static function serverError(int $statusCode): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_SERVER_ERROR, 'HTTP_SERVER_ERROR', "HTTP server error with status code: {$statusCode}" - )); + ); } } diff --git a/src/Network/NetworkException.php b/src/Network/NetworkException.php index d54df19..314af6a 100644 --- a/src/Network/NetworkException.php +++ b/src/Network/NetworkException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Network; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class NetworkException extends AbstractException { @@ -14,19 +13,19 @@ final class NetworkException extends AbstractException public static function connectionFailed(string $host): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_CONNECTION_FAILED, 'CONNECTION_FAILED', "Failed to connect to host: {$host}" - )); + ); } public static function timeout(string $operation): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_TIMEOUT, 'TIMEOUT', "Network operation timed out: {$operation}" - )); + ); } } diff --git a/src/Queue/QueueException.php b/src/Queue/QueueException.php index 312438b..e598c18 100644 --- a/src/Queue/QueueException.php +++ b/src/Queue/QueueException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Queue; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class QueueException extends AbstractException { @@ -15,28 +14,28 @@ final class QueueException extends AbstractException public static function jobPushFailed(string $jobClass): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_JOB_PUSH_FAILED, 'JOB_PUSH_FAILED', "Failed to push job to queue: {$jobClass}" - )); + ); } public static function jobProcessingFailed(string $jobId): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_JOB_PROCESSING_FAILED, 'JOB_PROCESSING_FAILED', "Failed to process job: {$jobId}" - )); + ); } public static function queueConnectionFailed(string $connection): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_QUEUE_CONNECTION_FAILED, 'QUEUE_CONNECTION_FAILED', "Failed to connect to queue: {$connection}" - )); + ); } } diff --git a/src/Routing/RoutingException.php b/src/Routing/RoutingException.php index b1297bc..56e54af 100644 --- a/src/Routing/RoutingException.php +++ b/src/Routing/RoutingException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Routing; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class RoutingException extends AbstractException { @@ -14,19 +13,19 @@ final class RoutingException extends AbstractException public static function routeNotFound(string $uri): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_ROUTE_NOT_FOUND, 'ROUTE_NOT_FOUND', "Route not found for URI: {$uri}" - )); + ); } public static function methodNotAllowed(string $method, string $uri): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_METHOD_NOT_ALLOWED, 'METHOD_NOT_ALLOWED', "Method {$method} not allowed for URI: {$uri}" - )); + ); } } diff --git a/src/Runtime/RuntimeException.php b/src/Runtime/RuntimeException.php index 30b440f..4dcd194 100644 --- a/src/Runtime/RuntimeException.php +++ b/src/Runtime/RuntimeException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Runtime; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class RuntimeException extends AbstractException { @@ -15,28 +14,28 @@ final class RuntimeException extends AbstractException public static function unexpectedValue(string $details): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_UNEXPECTED_VALUE, 'UNEXPECTED_VALUE', "Unexpected value: {$details}" - )); + ); } public static function outOfMemory(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_OUT_OF_MEMORY, 'OUT_OF_MEMORY', 'Out of memory error' - )); + ); } public static function classNotFound(string $className): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_CLASS_NOT_FOUND, 'CLASS_NOT_FOUND', "Class not found: {$className}" - )); + ); } } diff --git a/src/Security/EncryptionException.php b/src/Security/EncryptionException.php index 472dc5b..41c2d01 100644 --- a/src/Security/EncryptionException.php +++ b/src/Security/EncryptionException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Security; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class EncryptionException extends AbstractException { @@ -14,19 +13,19 @@ final class EncryptionException extends AbstractException public static function encryptionFailed(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_ENCRYPTION_FAILED, 'ENCRYPTION_FAILED', 'Encryption operation failed' - )); + ); } public static function decryptionFailed(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_DECRYPTION_FAILED, 'DECRYPTION_FAILED', 'Decryption operation failed' - )); + ); } } diff --git a/src/Security/SecurityException.php b/src/Security/SecurityException.php index 2afb3ea..ffb543f 100644 --- a/src/Security/SecurityException.php +++ b/src/Security/SecurityException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Security; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class SecurityException extends AbstractException { @@ -15,28 +14,28 @@ final class SecurityException extends AbstractException public static function unauthorized(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_UNAUTHORIZED, 'UNAUTHORIZED', 'Unauthorized access' - )); + ); } public static function csrfTokenMismatch(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_CSRF_TOKEN_MISMATCH, 'CSRF_TOKEN_MISMATCH', 'CSRF token mismatch' - )); + ); } public static function rateLimitExceeded(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_RATE_LIMIT_EXCEEDED, 'RATE_LIMIT_EXCEEDED', 'Rate limit exceeded' - )); + ); } } diff --git a/src/Session/SessionException.php b/src/Session/SessionException.php index 694b56b..2802c60 100644 --- a/src/Session/SessionException.php +++ b/src/Session/SessionException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Session; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class SessionException extends AbstractException { @@ -14,19 +13,19 @@ final class SessionException extends AbstractException public static function sessionStartFailed(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_SESSION_START_FAILED, 'SESSION_START_FAILED', 'Failed to start session' - )); + ); } public static function invalidSessionId(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_INVALID_SESSION_ID, 'INVALID_SESSION_ID', 'Invalid session ID' - )); + ); } } diff --git a/src/System/SystemException.php b/src/System/SystemException.php index 4a4379d..7482340 100644 --- a/src/System/SystemException.php +++ b/src/System/SystemException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\System; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class SystemException extends AbstractException { @@ -15,28 +14,28 @@ final class SystemException extends AbstractException public static function resourceUnavailable(string $resource): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_RESOURCE_UNAVAILABLE, 'RESOURCE_UNAVAILABLE', "System resource unavailable: {$resource}" - )); + ); } public static function environmentError(string $details): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_ENVIRONMENT_ERROR, 'ENVIRONMENT_ERROR', "Environment error: {$details}" - )); + ); } public static function extensionNotLoaded(string $extension): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_EXTENSION_NOT_LOADED, 'EXTENSION_NOT_LOADED', "PHP extension not loaded: {$extension}" - )); + ); } } diff --git a/src/Template/TemplateException.php b/src/Template/TemplateException.php index 9536cc2..9b6b487 100644 --- a/src/Template/TemplateException.php +++ b/src/Template/TemplateException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Template; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class TemplateException extends AbstractException { @@ -14,19 +13,19 @@ final class TemplateException extends AbstractException public static function templateNotFound(string $templateName): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_TEMPLATE_NOT_FOUND, 'TEMPLATE_NOT_FOUND', "Template not found: {$templateName}" - )); + ); } public static function renderingFailed(string $templateName): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_RENDERING_FAILED, 'RENDERING_FAILED', "Failed to render template: {$templateName}" - )); + ); } } diff --git a/src/Validation/RuleViolationException.php b/src/Validation/RuleViolationException.php index bd1931f..0f64242 100644 --- a/src/Validation/RuleViolationException.php +++ b/src/Validation/RuleViolationException.php @@ -5,7 +5,6 @@ namespace KaririCode\Exception\Validation; use KaririCode\Exception\AbstractException; -use KaririCode\Exception\ExceptionMessage; final class RuleViolationException extends AbstractException { @@ -13,10 +12,10 @@ final class RuleViolationException extends AbstractException public static function create(string $rule, string $field): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_RULE_VIOLATION, 'RULE_VIOLATION', "Validation rule '{$rule}' violated for field '{$field}'" - )); + ); } } diff --git a/src/Validation/ValidationException.php b/src/Validation/ValidationException.php index 8bfb6e4..27e23d9 100644 --- a/src/Validation/ValidationException.php +++ b/src/Validation/ValidationException.php @@ -6,7 +6,6 @@ use KaririCode\Exception\AbstractException; use KaririCode\Exception\Contract\ErrorMessage; -use KaririCode\Exception\ExceptionMessage; final class ValidationException extends AbstractException { @@ -16,11 +15,11 @@ final class ValidationException extends AbstractException public static function create(): self { - return new self(new ExceptionMessage( + return self::createException( self::CODE_VALIDATION_FAILED, 'VALIDATION_FAILED', 'Validation failed' - )); + ); } public function addError(string $field, ErrorMessage $errorMessage): self