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.
Installation
composer require timefrontiers/php-has-errors
Requirements
- PHP 8.1+
- (Optional)
timefrontiers/php-instance-errorfor 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 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 timefrontiers/php-has-errors 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Bootstraps errors and handles them via reporters and renderers
Trait providing methods to set class properties with an array.
Expansion traits for Yii2 components
Traits to build collections of specific objects
Asynchronous Sentry for Symfony - Fire and forget
KISS implementation of RequestTrait with usage of CURL
统计信息
- 总下载量: 22
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 38
- 依赖项目数: 4
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-04-15