hradigital/php-exceptions-laravel
Composer 安装命令:
composer require hradigital/php-exceptions-laravel
包简介
Laravel wrapper for hradigital/php-exceptions, wiring Laravel's error handling and providing a JSON Renderer for these Exceptions.
README 文档
README
Laravel wiring + JSON renderer for hradigital/php-exceptions.
The base library ships platform-agnostic domain exceptions (AbstractBaseException and the Client/+Server/ trees, aligned with HTTP 4xx/5xx semantics). This package translates them into a uniform JSON response at the HTTP boundary and auto-registers itself with Laravel's exception handler, but only for API requests — browser requests still fall through to Laravel's default error pages.
| Package | hradigital/php-exceptions-laravel |
|---|---|
| Namespace | HraDigital\Components\ExceptionRenderer |
| Requires | PHP ^8.1, hradigital/php-exceptions ^1.0 |
| Laravel | ^10.0 · ^11.0 · ^12.0 |
| License | GPL-3.0-or-later |
Installation
composer require hradigital/php-exceptions-laravel
Registration
The service provider is auto-discovered — no manual registration needed in most apps. If auto-discovery is disabled for this package, register it explicitly:
Laravel 11 / 12 — bootstrap/providers.php:
return [ HraDigital\Components\ExceptionRenderer\ExceptionsServiceProvider::class, ];
Laravel 10 (and below) — config/app.php:
'providers' => ServiceProvider::defaultProviders()->merge([ HraDigital\Components\ExceptionRenderer\ExceptionsServiceProvider::class, ])->toArray(),
What the provider does
On boot(), the provider:
- Binds
ExceptionRendereras a singleton in the container (so app code can resolve it and add custom strategies). - Hooks into Laravel's exception handler via
renderable(), intercepting any thrownAbstractBaseException.
The hook only renders when the incoming request is treated as an API request:
| Signal | Detected via |
|---|---|
Accept header negotiates JSON |
$request->expectsJson() / wantsJson() |
| Request body is JSON | $request->isJson() |
URL path matches api/* (or is exactly api) |
$request->is('api/*') |
Matched route name starts with api. |
$request->route()?->getName() |
For any other request, the callback returns null, so Laravel's default handler keeps rendering its usual HTML / Whoops / Blade error pages.
Response shapes
Default
Any AbstractBaseException rendered via DefaultRenderer:
{
"message": "Resource not found.",
"code": 404,
"data": { "id": 42 }
}
data is omitted when the exception was raised without structured payload (hasData() === false).
Input / validation failures
Exceptions implementing HraDigital\Components\Exceptions\Client\Request\RequestFailureInterface are rendered via InputFailureRenderer:
{
"message": "Invalid input.",
"code": 422,
"rules": { "email": ["required"] },
"failed": [
{ "fieldName": "email", "message": "email is required" }
]
}
rules mirrors getFailures() (the field-keyed rule list). failed is the flattened, per-message list derived from getFailedMessages() — one entry per {fieldName, message} pair, preserving field order.
Adding a custom renderer strategy
Resolve the singleton and prepend a strategy. The first strategy whose supports() returns true wins; the bundled DefaultRenderer is the always-matching fallback.
use HraDigital\Components\ExceptionRenderer\ExceptionRenderer; use HraDigital\Components\ExceptionRenderer\Renderers\ExceptionRendererInterface; use HraDigital\Components\Exceptions\AbstractBaseException; use Symfony\Component\HttpFoundation\JsonResponse; final class TenantQuotaRenderer implements ExceptionRendererInterface { public function supports(AbstractBaseException $exception): bool { return $exception instanceof \App\Exceptions\TenantQuotaExceeded; } public function renderAsJson(AbstractBaseException $exception): JsonResponse { return new JsonResponse([ 'message' => $exception->getMessage(), 'code' => $exception->getCode(), 'tenant' => $exception->getData()['tenant'] ?? null, ], $exception->getCode()); } } // In a service provider's boot(): app(ExceptionRenderer::class)->add(new TenantQuotaRenderer());
add() always prepends, so later registrations override earlier ones.
Public API
| Class / interface | Purpose |
|---|---|
ExceptionRenderer |
Strategy dispatcher; renderAsJson(), add(), getStrategies(), factory. |
Renderers\ExceptionRendererInterface |
Contract every strategy implements (supports() + renderAsJson()). |
Renderers\DefaultRenderer |
Always-matching fallback; emits the default response shape. |
Renderers\InputFailureRenderer |
Matches RequestFailureInterface; emits validation-failure shape. |
ExceptionsServiceProvider |
Singleton binding + Laravel renderable() hook with API-request gating. |
Local development
composer install composer ci # lint + phpcs + phpstan + phpunit composer test # phpunit only composer cs # PSR-12 check composer cs:fix # PSR-12 autofix composer stan # phpstan (level 6)
Continuous Integration
.github/workflows/ci.yml runs on every push and PR to master. It executes lint → phpcs → phpstan → phpunit against the supported PHP × Laravel matrix:
| Laravel 10 | Laravel 11 | Laravel 12 | |
|---|---|---|---|
| 8.1 | ✓ | ||
| 8.2 | ✓ | ✓ | ✓ |
| 8.3 | ✓ | ✓ | |
| 8.4 | ✓ |
The workflow pins illuminate/* and orchestra/testbench per matrix cell with composer require --no-update before installing.
Testing
The tests/ suite covers every class in the package:
ExceptionRendererTest— factory wiring, fallback path, strategy routing, prepend ordering, custom-constructor wiring.Renderers/DefaultRendererTest— status/message/code mapping, conditionaldatakey.Renderers/InputFailureRendererTest— flattening offailed,rulesmirroring, empty-payload behaviour.ExceptionsServiceProviderTest— Testbench-based: singleton binding, end-to-end HTTP rendering for JSON /api/*requests, and direct callback invocation proving non-API requests pass through (nullreturn).Support/Stubs— shared anonymous-class factories for a generic exception and aRequestFailureInterfaceexception, excluded from the test suite.
License
GPL-3.0-or-later — see LICENSE. This matches the upstream hradigital/php-exceptions license.
hradigital/php-exceptions-laravel 适用场景与选型建议
hradigital/php-exceptions-laravel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 05 月 05 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「json」 「exceptions」 「renderer」 「laravel」 「hradigital」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 hradigital/php-exceptions-laravel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 hradigital/php-exceptions-laravel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 hradigital/php-exceptions-laravel 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
php7ify is a project that brings new php7 classes and exceptions to php 5.x.
The CodenamePHP Platform core that contains basic interfaces, exceptions etc..
Kinikit - PHP Application development framework MVC component
ext-json wrapper with sane defaults
Bootstraps errors and handles them via reporters and renderers
A package to cast json fields, each sub-keys is castable
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 43
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: GPL-3.0-or-later
- 更新时间: 2026-05-05