hosmelq/fault-php
Composer 安装命令:
composer require hosmelq/fault-php
包简介
Composable helpers for wrapping and aggregating PHP exceptions with codes, context, origins, and clear internal and user messages.
README 文档
README
Composable helpers for wrapping and aggregating PHP exceptions with codes, context, origins, and clear internal and user messages.
Introduction
Wrap errors with rich, structured metadata and traverse entire exception chains ergonomically. Attach user‑facing and internal messages, codes, call‑site origins, and context, then extract them consistently for logging and display.
use Throwable; use HosmelQ\Fault\Fault; use HosmelQ\Fault\Wrap; try { // Some operation that can fail } catch (Throwable $error) { // Wrap with user + internal messages, a code, and context $fault = Fault::wrap( $error, Wrap::code('err:stripe:payment:insufficient_funds'), Wrap::internal('Stripe API returned 402: insufficient_funds'), Wrap::public('Your payment could not be processed. Please try again later.'), Wrap::context(['customer_id' => 'cust_123', 'payment_method' => 'card_456']), Wrap::origin(), ); throw $fault; // Re‑throw enriched error } // Somewhere higher in the stack try { // Application entrypoint, controller action, etc. } catch (Throwable $error) { // Aggregate data across the whole chain $message = Fault::userMessage($error); // "Your payment could not be processed. Please try again later." $code = Fault::code($error); // "err:stripe:payment:insufficient_funds" $ctx = Fault::context($error); // ['customer_id' => 'cust_123', 'payment_method' => 'card_456'] $intern = Fault::internals($error); // ["Stripe API returned 402: insufficient_funds", "... base error ..."] $origins = Fault::origins($error); // [[file => '...', line => 123], ...] }
It produces a standard FaultException layer you can re‑throw and later traverse to extract codes, messages, context, and origins across nested exceptions.
Requirements
- PHP 8.4+
Installation & setup
Install the package via composer:
composer require hosmelq/fault-php
Basic usage
Getting started
Create a new fault with an internal message and attach wrappers for public text, codes, and context:
use HosmelQ\Fault\Fault; use HosmelQ\Fault\Wrap; $fault = Fault::new( 'Email validation failed', // internal message (developer‑facing) Wrap::public('Please check your email address.'), Wrap::code('err:validation:email:invalid_format'), Wrap::context(['field' => 'email', 'value' => 'invalid@']), ); // Extract values across the chain Fault::userMessage($fault); // "Please check your email address." Fault::internals($fault); // ["Email validation failed"] Fault::code($fault); // "err:validation:email:invalid_format" Fault::context($fault); // ['field' => 'email', 'value' => 'invalid@']
Wrapping existing throwables
Wrap any existing Throwable to add fault metadata without losing the original exception:
use Throwable; use HosmelQ\Fault\Fault; use HosmelQ\Fault\Wrap; try { // Code that might throw } catch (Throwable $error) { $fault = Fault::wrap( $error, Wrap::public('Failed to send email. Please verify the recipient address.'), Wrap::internal('SMTP server rejected message delivery'), Wrap::code('err:resend:email:smtp_failure'), ); throw $fault; }
Aggregating multiple errors
Combine multiple throwables into a single fault envelope for batch operations:
use HosmelQ\Fault\Fault; use HosmelQ\Fault\Wrap; $errors = [$mysqlError, $redisError, $resendError]; $combined = Fault::combine( $errors, Wrap::public('Multiple service failures occurred. Please try again later.') ); // The previous exception is an AggregateFault with the original errors $prev = $combined->getPrevious(); // User‑facing message is taken from the newest layers first Fault::publicMessages($combined); // ['Multiple service failures occurred. Please try again later.']
Merging context newest‑first
Merge context newest‑first. Newer layer values override older ones:
$root = Fault::new( 'Payment processing failed', Wrap::context(['env' => 'prod', 'customer_id' => 'cust_123']) ); $wrap = Fault::wrap( $root, Wrap::context(['customer_id' => 'cust_456', 'payment_method' => 'card_789']) ); $merged = Fault::context($wrap); // ['customer_id' => 'cust_456', 'payment_method' => 'card_789', 'env' => 'prod']
Capturing origins
Capture the file and line where a layer is added, then collect unique origins across the chain:
use HosmelQ\Fault\Fault; use HosmelQ\Fault\Wrap; $base = Fault::new('Database connection failed'); $a = Fault::wrap($base, Wrap::origin()); // captures this call site $b = Fault::wrap($a, Wrap::origin()); $origins = Fault::origins($b); // [ ['file' => '/path/To/File.php', 'line' => 123], ... ]
Using enums
Enums are accepted anywhere a message or code is expected. Backed enums use value, and unit enums use name:
use HosmelQ\Fault\Wrap; enum ErrorCode: int { case NotFound = 404; } enum Notice: string { case Failure = 'failure'; } enum Level { case Warning; } Wrap::code(ErrorCode::NotFound); Wrap::internal(Notice::Failure); Wrap::public(Level::Warning);
Testing
composer test
Changelog
Please see CHANGELOG.md for more information on what has changed recently.
Credits
Based on:
License
The MIT License (MIT). Please see License File for more information.
hosmelq/fault-php 适用场景与选型建议
hosmelq/fault-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 09 月 20 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「exception」 「Context」 「fault」 「aggregation」 「error-handling」 「wrapping」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 hosmelq/fault-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 hosmelq/fault-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 hosmelq/fault-php 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Behat Context for testing Symfony Api
Retry tasks that fail due to transient faults
Context support (request, session and application scope) for n2n framework.
Circuit Breaker library
Standalone CLI that generates codebase context (JSON + Markdown) for AI agents.
A library providing abstract implementations of various persistence layers based on JSON API relational resource concepts.
统计信息
- 总下载量: 4
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 27
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-09-20