pnoexz/php-api-exception 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

pnoexz/php-api-exception

Composer 安装命令:

composer require pnoexz/php-api-exception

包简介

PHP Exceptions

README 文档

README

PHP API Exception relies on the following principles:

Signature

/**
 * @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)

Examples

Simple usage

<?php

namespace Pnoexz\Examples\Exceptions;

use Pnoexz\ApiException\Http\ClientError\NotFoundException;

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

Will output the following JSON:

{
  "class": "Pnoexz\\Examples\\Exceptions\\ArticleNotFoundException",
  "message": "Article not found",
  "statusCode": 404
}

Creating a custom exception

If you need to support an HTTP Status Code that's not on the standard or is missing, it's possible to extend from \Pnoexz\ApiException\Http\ClientError\ClientErrorException (default level WARNING), \Pnoexz\ApiException\Http\ServerError\ServerErrorException (default level ERROR) or Pnoexz\ApiException (no default level).

<?php

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

Sending extra data to the client along with the exception

Suppose we are building an ecommerce system in which users can't have more than one pending cart at the same time. If the user tries to create a new cart, instead of simply displaying an error, we can send the entity to the client so they can gracefully handle the error and display information to the user.

Exception

<?php

namespace Pnoexz\Examples\Exceptions;

use Pnoexz\ApiException\Http\ClientError\ConflictException;

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

From the service

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

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

Output to the client

{
  "class": "Pnoexz\\Examples\\Exceptions\\PendingCartExistsException",
  "message": "A pending cart already exists",
  "statusCode": 409,
  "data": {
    "cart": {
      "id": 8,
      "items": [
          {"id": 8931}
      ]
    }
  }
}

Maintaining the previously thrown exception

In this case, we will be catching an exception that contains sensitive data (a raw SQL query). We need to separate what the client will see and what we should log. This might require some extra code in our handler, but when throwing the exception, all we need to do is the pass what we caught to the second parameter.

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

We can then catch this exception from the calling method and do similarly; maintaining the exception trace and sending back a nice output to the client.

Handler

These examples use the Slim3 error handler but should work similarly with other frameworks.

Handling only ApiExceptions

    /**
     * @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());
    }

Handling all exceptions

    /**
     * @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);
    }

pnoexz/php-api-exception 适用场景与选型建议

pnoexz/php-api-exception 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 436 次下载、GitHub Stars 达 0, 最近一次更新时间为 2018 年 08 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 pnoexz/php-api-exception 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 pnoexz/php-api-exception 我们能提供哪些服务?
定制开发 / 二次开发

基于 pnoexz/php-api-exception 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 436
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 8
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-08-05