PHP code example of pnoexz / php-api-exception

1. Go to this page and download the library: Download pnoexz/php-api-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/ */

    

pnoexz / php-api-exception example snippets


/**
 * @param array           $data     Any JSON serializable data we should
 *                                  send to the user along with the built-in
 *                                  information
 * @param \Throwable|null $previous The previous exception thrown to
 *                                  maintain the exception chain
 */
ApiExceptionL::__construct(array $data = [], \Throwable $previous = null)



namespace Pnoexz\Examples\Exceptions;

use Pnoexz\ApiException\Http\ClientError\NotFoundException;

class ArticleNotFoundException extends NotFoundException
{
    /**
     * @var string
     */
    public $message = "Article not found";
}



namespace Pnoexz\Examples\Exceptions;

use Pnoexz\ApiException;

class ArticleNotFoundException extends ApiException
{
    /**
     * @var int
     */
    protected $httpStatus = 701;

    /**
     * @var string
     */
    protected $level = \Psr\Log\LogLevel::WARNING;

    /**
     * @var string
     */
    public $message = "Article not found";
}



namespace Pnoexz\Examples\Exceptions;

use Pnoexz\ApiException\Http\ClientError\ConflictException;

class PendingCartExistsException extends ConflictException
{
    /**
     * @var string
     */
    public $message = "A pending cart already exists";
}

$potentiallyPendingCart = $this->getPendingCartByUser($user);

if (!empty($potentiallyPendingCart)) {
    throw new PendingCartExistsException(['cart' => $potentiallyPendingCart]);
}


class FruitRepository
{
    public function get(int $id)
    {
        try {
            $sth = $this->dbh->prepare("
                SELECT name, colour, calories
                FROM fruit
                WHERE id = :id
            ");

            $sth->execute([':id' => $id]);
            return $sth->fetch(PDO::FETCH_ASSOC);
        } catch (\Exception $e) {
            throw new DatabaseException([], $e);
        }
    }
}

    /**
     * @param Request    $request
     * @param Response   $response
     * @param \Throwable $throwable
     * @return Response
     */
    public function __invoke(
        Request $request,
        Response $response,
        ApiException $exception
    ) {
        $encodedBody = \json_encode($exception);

        $this->log(
            $exception->getLevel(),
            $exception->getMessage(),
            $encodedBody
        );

        return $response->withJson($encodedBody, $exception->getStatusCode());
    }

    /**
     * @param Request    $request
     * @param Response   $response
     * @param \Throwable $throwable
     * @return Response
     */
    public function __invoke(
        Request $request,
        Response $response,
        \Throwable $throwable
    ) {
        $statusCode = 500;
        $level = LogLevel::ERROR;
        $message = $throwable->getMessage();

        if ($throwable instanceof ApiException) {
            $statusCode = $throwable->getStatusCode();
            $level = $throwable->getLevel();
        }

        $body = [
            'statusCode' => $statusCode,
            'level' => $level,
            'message' => $message,
        ];

        $this->log($level, $message, $body);

        return $response->withJson($body, $statusCode);
    }