PHP code example of kariricode / exception

1. Go to this page and download the library: Download kariricode/exception library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kariricode / exception example snippets




declare(strict_types=1);

namespace YourApp\Controller;

use YourApp\Service\UserService;
use KaririCode\Contract\Http\Response;
use KaririCode\Contract\Http\ServerRequest;
use KaririCode\Router\Attributes\Route;

final class UserController extends BaseController
{
    public function __construct(private UserService $userService)
    {
    }

    #[Route('/user/{userId}', methods: ['GET'])]
    public function getUserData(ServerRequest $request, Response $response): Response
    {
        $userId = (int)$request->getAttribute('userId');

        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);
        }
    }
}

// UserService.php
namespace YourApp\Service;

use YourApp\Repository\UserRepository;
use KaririCode\Contract\Log\Logger;
use KaririCode\Exception\Database\DatabaseException;

class UserService
{
    public function __construct(
        private UserRepository $userRepository,
        private Logger $logger
    ) {
    }

    /**
     * @throws DatabaseException
     */
    public function getUserData(int $userId): array
    {
        try {
            return $this->userRepository->findUserById($userId);
        } catch (DatabaseException $e) {
            $this->logger->error('Failed to retrieve user data', [
                'userId' => $userId,
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }
}

// UserRepository.php
namespace YourApp\Repository;

use KaririCode\Contract\Database\EntityManager;
use KaririCode\Exception\Database\DatabaseException;

class UserRepository
{
    public function __construct(private EntityManager $entityManager)
    {
    }

    /**
     * @throws DatabaseException
     */
    public function findUserById(int $userId): array
    {
        $sql = 'SELECT * FROM users WHERE id = ?';
        try {
            $userData = $this->entityManager->query($sql, [$userId]);

            if (empty($userData)) {
                throw DatabaseException::recordNotFound('User', $userId);
            }

            return $userData;
        } catch (\Exception $e) {
            throw DatabaseException::queryError($sql, $e->getMessage());
        }
    }
}



declare(strict_types=1);

namespace YourApp\Exception;

use KaririCode\Exception\AbstractException;

final class OrderException extends AbstractException
{
    private const CODE_ORDER_LIMIT_EXCEEDED = 4001;

    public static function orderLimitExceeded(float $totalAmount, float $userOrderLimit): self
    {
        return self::createException(
            self::CODE_ORDER_LIMIT_EXCEEDED,
            'ORDER_LIMIT_EXCEEDED',
            "Order amount (${totalAmount}) exceeds user limit (${userOrderLimit})"
        );
    }
}



declare(strict_types=1);

namespace YourApp\Service;

use YourApp\Exception\OrderException;
use YourApp\Repository\OrderRepository;
use KaririCode\Contract\Log\Logger;
use KaririCode\Exception\Database\DatabaseException;

final class OrderService
{
    public function __construct(
        private OrderRepository $orderRepository,
        private Logger $logger
    ) {
    }

    /**
     * @throws OrderException
     * @throws DatabaseException
     */
    public function placeOrder(int $userId, array $items, float $totalAmount): void
    {
        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;
        }
    }
}