jeromejhipolito/laravel-global-error-formatter
Composer 安装命令:
composer require jeromejhipolito/laravel-global-error-formatter
包简介
Global error/exception handler for Laravel APIs. Standardized JSON error responses with configurable exception mappings.
README 文档
README
Global error/exception handler for Laravel APIs. Provides standardized JSON error responses with configurable exception mappings.
Features
- Global exception handling for all API errors
- Consistent JSON error response format
- Configurable exception mappings (add your own exceptions)
- Built-in handling for common Laravel exceptions
- Customizable response structure
- First-error or all-errors validation format
- Environment-based debug info (trace & error details)
- Translation support for error messages
- Base FormRequest class for consistent validation errors
Requirements
- PHP 8.2+
- Laravel 11.0+ or 12.0+
Installation
composer require jeromejhipolito/laravel-global-error-formatter
The package will auto-register its service provider.
Configuration
Publish the configuration file:
php artisan vendor:publish --tag=global-error-formatter-config
Quick Start
Register in bootstrap/app.php
use JeromeJHipolito\GlobalErrorFormatter\GlobalErrorFormatter; return Application::configure(basePath: dirname(__DIR__)) ->withExceptions(function (Exceptions $exceptions) { GlobalErrorFormatter::register($exceptions); }) ->create();
That's it! All exceptions in API requests will now return consistent JSON responses.
Response Format
{
"status": "error",
"message": "Resource not found.",
"errors": null,
"trace": null
}
Environment-Based Error Details
The package automatically shows/hides error details based on your environment:
// config/global-error-formatter.php // Stack trace - only shown in debug mode 'include_trace' => env('GLOBAL_ERROR_INCLUDE_TRACE', env('APP_DEBUG', false)), // Error details (exception message) - only shown in debug mode 'include_error_details' => env('GLOBAL_ERROR_DETAILS', env('APP_DEBUG', false)),
Development (APP_DEBUG=true):
{
"status": "error",
"message": "Something went wrong.",
"errors": "SQLSTATE[42S02]: Base table or view not found...",
"trace": [...]
}
Production (APP_DEBUG=false):
{
"status": "error",
"message": "Something went wrong."
}
Adding Custom Exceptions
Via Configuration
// config/global-error-formatter.php 'exceptions' => [ \App\Exceptions\PaymentException::class => [ 'status' => 402, 'message' => 'Payment required.', ], \App\Exceptions\CouponException::class => [ 'status' => 400, 'message' => null, // Uses exception's getMessage() ], ],
Programmatically
use JeromeJHipolito\GlobalErrorFormatter\GlobalErrorFormatter; return Application::configure(basePath: dirname(__DIR__)) ->withExceptions(function (Exceptions $exceptions) { $formatter = app(GlobalErrorFormatter::class); $formatter ->addException(PaymentException::class, 402, 'Payment required.') ->addException(CouponException::class, 400); // Uses exception message $exceptions->render(function (Throwable $e, Request $request) use ($formatter) { if ($request->expectsJson()) { return $formatter->format($e); } return null; }); }) ->create();
Built-in Exception Handling
| Exception | Status | Default Message |
|---|---|---|
ModelNotFoundException |
404 | Resource not found. |
NotFoundHttpException |
404 | Route not found. |
AuthenticationException |
401 | Unauthenticated. |
AuthorizationException |
403 | Unauthorized. |
ValidationException |
422 | First validation error |
ThrottleRequestsException |
429 | Too many requests. |
| Other exceptions | 500 | Something went wrong. |
Using BaseFormRequest
Extend BaseFormRequest for consistent validation error responses:
use JeromeJHipolito\GlobalErrorFormatter\BaseFormRequest; class CreateUserRequest extends BaseFormRequest { public function authorize(): bool { return true; } public function rules(): array { return [ 'email' => 'required|email|unique:users', 'password' => 'required|min:8', ]; } }
Validation errors will automatically use the configured format.
Configuration Options
Response Keys
Customize the JSON response structure:
'response_keys' => [ 'status' => 'status', // Change to 'result', 'success', etc. 'message' => 'message', // Change to 'msg', 'error', etc. 'errors' => 'errors', // Change to 'details', 'data', etc. 'trace' => 'trace', // Change to 'stack', 'debug', etc. ],
Status Values
Customize the status field values:
'status_values' => [ 'success' => 'success', 'error' => 'error', // Change to 'failed', 'failure', etc. ],
Validation Format
Choose how validation errors are returned:
// 'first' - Only the first error message (default) 'validation_format' => 'first', // 'all' - All errors with field names 'validation_format' => 'all',
First format response:
{
"status": "error",
"message": "The email field is required."
}
All format response:
{
"status": "error",
"message": "Validation failed.",
"errors": {
"email": ["The email field is required."],
"password": ["The password must be at least 8 characters."]
}
}
Translation Support
// Pass messages through trans() helper 'translate_messages' => true,
This allows you to create translation files for error messages:
// lang/ja/messages.php return [ 'Resource not found.' => 'リソースが見つかりません。', 'Validation failed.' => '検証に失敗しました。', ];
Conditional Registration
Only handle specific requests:
GlobalErrorFormatter::register($exceptions, function (Throwable $e, Request $request) { // Only handle API routes return $request->is('api/*'); });
Override Default Messages
'defaults' => [ 'model_not_found' => [ 'status' => 404, 'message' => 'The requested item was not found.', ], 'authentication' => [ 'status' => 401, 'message' => 'Please log in to continue.', ], // ... other defaults ],
Testing
composer test
License
The MIT License (MIT). Please see License File for more information.
Credits
jeromejhipolito/laravel-global-error-formatter 适用场景与选型建议
jeromejhipolito/laravel-global-error-formatter 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 11 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 02 月 02 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「json」 「api」 「exception」 「error」 「response」 「formatter」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 jeromejhipolito/laravel-global-error-formatter 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 jeromejhipolito/laravel-global-error-formatter 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 jeromejhipolito/laravel-global-error-formatter 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Kinikit - PHP Application development framework MVC component
ext-json wrapper with sane defaults
A package to cast json fields, each sub-keys is castable
A PSR-7 compatible library for making CRUD API endpoints
swagger-php - Generate interactive documentation for your RESTful API using phpdoc annotations
Get wordpress nav menus and share the main site menus with the child sites.
统计信息
- 总下载量: 11
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 31
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-02-02