定制 anil/exception-response 二次开发

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

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

anil/exception-response

Composer 安装命令:

composer require anil/exception-response

包简介

Drop-in JSON exception responses for Laravel 11, 12, and 13 APIs.

README 文档

README

tests static analysis code style coverage License: MIT

Drop-in JSON exception responses for Laravel 11, 12, and 13 APIs — built for the slim application skeleton (no app/Exceptions/Handler.php).

  • ✅ Uniform JSON shape for every exception
  • ✅ Translatable messages (English + Spanish included; bring your own locales)
  • ✅ Stable machine-readable error_code for clients
  • ✅ Debug-mode trace info gated by app.debug
  • ExceptionRendered event for logging / Sentry tagging
  • ✅ Web routes untouched

Requirements

  • PHP 8.2+
  • Laravel 11.x, 12.x, or 13.x

Installation

composer require anilkumarthakur/laravel-exception-response

The service provider is auto-discovered.

Usage

Register the renderers inside bootstrap/app.php:

use AnilKumarThakur\ExceptionResponse\JsonExceptions;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        JsonExceptions::register($exceptions);
    })
    ->create();

Any request matching api/* or sending Accept: application/json will get a uniform JSON payload:

{
  "message": "Resource not found.",
  "error_code": "not_found"
}

Web routes still render the standard Laravel error pages.

Response shape

Field Always present Notes
message yes Localized; uses the exception's own message when set, otherwise the translated default
error_code when include_error_code (default true) Stable string like unauthenticated, validation_failed
errors only on ValidationException Field-level validation errors
exception when include_exception_class is true FQCN of the thrown exception
file, line, trace when app.debug and include_trace_in_debug are both true trace is truncated to trace_depth frames

Handled exceptions

Exception Status error_code
ValidationException 422 validation_failed (with errors)
AuthenticationException 401 unauthenticated
AuthorizationException 403 unauthorized
ModelNotFoundException 404 model_not_found
NotFoundHttpException 404 not_found
MethodNotAllowedHttpException 405 method_not_allowed
ThrottleRequestsException 429 too_many_requests
TokenMismatchException 419 csrf_token_mismatch
PostTooLargeException 413 payload_too_large
QueryException 500 query_error
BadMethodCallException 500 bad_method
InvalidArgumentException 400 invalid_argument
BindingResolutionException 500 binding_resolution
Any HttpExceptionInterface exception's status mapped from status when known

Configuration

Publish the config:

php artisan vendor:publish --tag=exception-response-config

config/exception-response.php:

return [
    'api_prefixes'             => ['api/*'],
    'include_exception_class'  => false,
    'include_trace_in_debug'   => true,
    'trace_depth'              => 10,
    'include_error_code'       => true,
];

Translations

Default messages live under lang/{locale}/messages.php. English and Spanish ship out of the box. Switch locale anywhere in your app (App::setLocale('es')) and responses follow.

Publish the lang files to override or add languages:

php artisan vendor:publish --tag=exception-response-lang

The translation keys (also used as error_code values):

unauthenticated, unauthorized, model_not_found, not_found, method_not_allowed,
too_many_requests, csrf_token_mismatch, payload_too_large, query_error,
bad_method, invalid_argument, binding_resolution, validation_failed, server_error

When the thrown exception has a custom message (e.g. abort(404, 'No such record.') or throw new AuthenticationException('Token expired.')), that message wins. Translations are used only when the exception carries the framework's default message or no message at all.

Events

Every JSON response dispatches AnilKumarThakur\ExceptionResponse\Events\ExceptionRendered:

use AnilKumarThakur\ExceptionResponse\Events\ExceptionRendered;
use Illuminate\Support\Facades\Event;

Event::listen(function (ExceptionRendered $event) {
    logger()->warning('API error', [
        'status'    => $event->response->getStatusCode(),
        'exception' => $event->exception::class,
        'path'      => $event->request->path(),
    ]);
});

Useful for Sentry / Bugsnag tagging, request-id correlation, or per-tenant alerting.

Extending

Register your own renderer alongside this one. Add it inside withExceptions() after JsonExceptions::register() — first-registered wins for matching exception types, so put the more specific callback first:

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (\App\Exceptions\PaymentFailed $e) {
        return response()->json([
            'message'    => $e->getMessage(),
            'error_code' => 'payment_failed',
        ], 402);
    });

    JsonExceptions::register($exceptions);
})

Development

composer install
composer test         # PHPUnit
composer analyse      # PHPStan level 10
composer format       # Pint (apply)
composer format:check # Pint (verify)
composer qa           # everything above

Architecture

src/
├── JsonExceptions.php                # public static API entry point
├── Renderer.php                      # registers per-exception render callbacks
├── ExceptionResponseServiceProvider.php
├── Events/
│   └── ExceptionRendered.php         # dispatched after every JSON response
└── Support/
    ├── RequestMatcher.php            # decides if a request wants JSON
    └── Payload.php                   # builds the response body
config/
└── exception-response.php
lang/
├── en/messages.php
└── es/messages.php
tests/
├── TestCase.php
├── Feature/
└── Unit/

Versioning, security, contributions

Changelog

See CHANGELOG.md.

License

MIT — see LICENSE.md.

anil/exception-response 适用场景与选型建议

anil/exception-response 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.58k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2023 年 03 月 31 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 anil/exception-response 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 4.58k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 13
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-03-31