定制 timefrontiers/php-has-errors 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

timefrontiers/php-has-errors

Composer 安装命令:

composer require timefrontiers/php-has-errors

包简介

Standardized error handling trait for PHP classes

README 文档

README

Standardized error handling trait for PHP classes with rank-based visibility filtering.

PHP Version License

Installation

composer require timefrontiers/php-has-errors

Requirements

  • PHP 8.1+
  • (Optional) timefrontiers/php-instance-error for advanced error extraction

Quick Start

use TimeFrontiers\Helper\HasErrors;

class PaymentService {
  use HasErrors;

  public function charge(float $amount):bool {
    if ($amount <= 0) {
      $this->_userError('charge', 'Amount must be positive');
      return false;
    }

    if (!$this->gateway->process($amount)) {
      $this->_systemError('charge', 'Gateway returned: ' . $this->gateway->lastError());
      $this->_userError('charge', 'Payment could not be processed. Please try again.');
      return false;
    }

    return true;
  }
}

// Usage
$payment = new PaymentService();
if (!$payment->charge(100.00)) {
  // Guest sees: "Payment could not be processed. Please try again."
  // Developer sees: "Gateway returned: Connection timeout" + user message
  $errors = (new InstanceError($payment))->get('charge');
}

Error Format

Errors are stored as arrays with 5 elements:

[$min_rank, $code, $message, $file, $line]
Index Name Type Description
0 min_rank int Minimum AccessRank to view this error
1 code int PHP error code (e.g., 256 = E_USER_ERROR)
2 message string Human-readable error message
3 file string Source file (auto-captured)
4 line int Line number (auto-captured)

AccessRank Enum

use TimeFrontiers\AccessRank;

AccessRank::GUEST;      // 0 - Public users
AccessRank::USER;       // 1 - Logged in users
AccessRank::ANALYST;    // 2
AccessRank::ADVERTISER; // 3
AccessRank::MODERATOR;  // 4 - Staff (can see internal errors)
AccessRank::EDITOR;     // 5
AccessRank::ADMIN;      // 6
AccessRank::DEVELOPER;  // 7 - Technical (can see system errors)
AccessRank::SUPERADMIN; // 8 - Can see debug errors
AccessRank::OWNER;      // 14 - Full access

Trait Methods

Core Methods

_addError()

Add an error with full control:

$this->_addError(
  context: 'save',
  message: 'Database connection failed',
  min_rank: AccessRank::DEVELOPER->value,
  code: 256
);
// File and line are auto-captured from caller

_mergeErrors()

Merge errors from another instance:

if (!$this->repository->save($entity)) {
  $this->_mergeErrors($this->repository, 'save', 'create');
  return false;
}

Helper Methods (Shortcuts)

Method Visible To Use For
_userError() Everyone (rank 0+) Validation, user input, friendly messages
_internalError() Staff (rank 4+) Business logic, process failures
_systemError() Developers (rank 7+) SQL errors, connections, system issues
_debugError() Superadmin (rank 8+) Sensitive debug info
// User sees this
$this->_userError('login', 'Invalid email or password');

// Only developers see this
$this->_systemError('login', "SQL: {$sql}\nError: {$db_error}");

Public Accessors

// Get all errors
$errors = $instance->getErrors();

// Check for errors
if ($instance->hasErrors('save')) { ... }
if ($instance->hasErrors()) { ... }  // Any context

// Count errors
$count = $instance->errorCount('save');
$total = $instance->errorCount();

// Clear errors
$instance->clearErrors('save');  // Specific context
$instance->clearErrors();        // All

// Get first error message
$message = $instance->firstError('save');
$message = $instance->firstError('save', AccessRank::GUEST->value);

// Get all messages
$messages = $instance->errorMessages('save');
$messages = $instance->errorMessages('save', AccessRank::GUEST->value);

Integration with InstanceError

use TimeFrontiers\InstanceError;

$service = new MyService();
if (!$service->process()) {
  // Get errors filtered by current user's rank
  $errors = (new InstanceError($service))->get('process');

  // Get all errors (bypass rank filter)
  $all = (new InstanceError($service, true))->get('process');

  // Get only messages
  $messages = (new InstanceError($service))->get('process', true);
}

Complete Example

use TimeFrontiers\Helper\HasErrors;
use TimeFrontiers\AccessRank;

class OrderService {
  use HasErrors;

  public function __construct(
    private OrderRepository $orders,
    private PaymentGateway $payment
  ) {}

  public function placeOrder(array $data):Order|false {
    // Validate
    if (empty($data['items'])) {
      $this->_userError('placeOrder', 'Cart is empty');
      return false;
    }

    // Create order
    $order = new Order($data);
    if (!$this->orders->save($order)) {
      $this->_mergeErrors($this->orders, 'save', 'placeOrder');
      $this->_userError('placeOrder', 'Unable to create order. Please try again.');
      return false;
    }

    // Process payment
    if (!$this->payment->charge($order->total)) {
      $this->_systemError('placeOrder', 'Payment failed: ' . $this->payment->lastError());
      $this->_userError('placeOrder', 'Payment declined. Please check your card details.');

      // Rollback
      $this->orders->delete($order);
      return false;
    }

    return $order;
  }
}

// Controller usage
$service = new OrderService($orders, $payment);

if ($order = $service->placeOrder($request->all())) {
  return Response::success('Order placed', $order);
}

// Get user-appropriate errors
$errors = (new InstanceError($service))->get('placeOrder', true);
return Response::error('Order failed', $errors);

Migration from Legacy Pattern

Before:

class MyClass {
  public $errors = [];

  public function doSomething():bool {
    if ($failed) {
      $this->errors['doSomething'][] = [0, 256, 'Failed', __FILE__, __LINE__];
      return false;
    }
    return true;
  }
}

After:

class MyClass {
  use HasErrors;

  public function doSomething():bool {
    if ($failed) {
      $this->_userError('doSomething', 'Failed');
      return false;
    }
    return true;
  }
}

License

MIT License

timefrontiers/php-has-errors 适用场景与选型建议

timefrontiers/php-has-errors 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 22 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 04 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「errors」 「trait」 「error-handling」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

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

围绕 timefrontiers/php-has-errors 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 22
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 38
  • 依赖项目数: 4
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-04-15