PHPackages                             anil/exception-response - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. anil/exception-response

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

anil/exception-response
=======================

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

v0.0.1(3y ago)04.6k[3 PRs](https://github.com/anilkumarthakur60/Exception-Response/pulls)MITPHPCI passing

Since Mar 31Pushed 3d ago1 watchersCompare

[ Source](https://github.com/anilkumarthakur60/Exception-Response)[ Packagist](https://packagist.org/packages/anil/exception-response)[ RSS](/packages/anil-exception-response/feed)WikiDiscussions 1.x Synced today

READMEChangelog (2)DependenciesVersions (16)Used By (0)

Laravel Exception Response
==========================

[](#laravel-exception-response)

[![tests](https://github.com/anilkumarthakur60/laravel-exception-response/actions/workflows/tests.yml/badge.svg)](https://github.com/anilkumarthakur60/laravel-exception-response/actions/workflows/tests.yml)[![static analysis](https://github.com/anilkumarthakur60/laravel-exception-response/actions/workflows/static-analysis.yml/badge.svg)](https://github.com/anilkumarthakur60/laravel-exception-response/actions/workflows/static-analysis.yml)[![code style](https://github.com/anilkumarthakur60/laravel-exception-response/actions/workflows/code-style.yml/badge.svg)](https://github.com/anilkumarthakur60/laravel-exception-response/actions/workflows/code-style.yml)[![coverage](https://github.com/anilkumarthakur60/laravel-exception-response/actions/workflows/coverage.yml/badge.svg)](https://github.com/anilkumarthakur60/laravel-exception-response/actions/workflows/coverage.yml)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](LICENSE.md)

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
------------

[](#requirements)

- PHP **8.2+**
- Laravel **11.x**, **12.x**, or **13.x**

Installation
------------

[](#installation)

```
composer require anilkumarthakur/laravel-exception-response
```

The service provider is auto-discovered.

Usage
-----

[](#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
--------------

[](#response-shape)

FieldAlways presentNotes`message`yesLocalized; 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` framesHandled exceptions
------------------

[](#handled-exceptions)

ExceptionStatus`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 statusmapped from status when knownConfiguration
-------------

[](#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
------------

[](#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
------

[](#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
---------

[](#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
-----------

[](#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
------------

[](#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
-----------------------------------

[](#versioning-security-contributions)

- Follows [Semantic Versioning](https://semver.org/). Breaking changes ship as a major version with notes in [UPGRADE.md](UPGRADE.md).
- Security issues: see [SECURITY.md](SECURITY.md). Please **do not** file public issues for vulnerabilities.
- Contributions welcome — see [CONTRIBUTING.md](CONTRIBUTING.md).

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md).

License
-------

[](#license)

MIT — see [LICENSE.md](LICENSE.md).

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance65

Regular maintenance activity

Popularity17

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 86.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~376 days

Total

4

Last Release

60d ago

Major Versions

0.x-dev → 1.x-dev2026-05-04

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/16583802?v=4)[Er. Anil Kumar Thakur](/maintainers/anilkumarthakur60)[@anilkumarthakur60](https://github.com/anilkumarthakur60)

---

Top Contributors

[![anilkumarthakur60](https://avatars.githubusercontent.com/u/16583802?v=4)](https://github.com/anilkumarthakur60 "anilkumarthakur60 (26 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (3 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (1 commits)")

### Embed Badge

![Health badge](/badges/anil-exception-response/health.svg)

```
[![Health](https://phpackages.com/badges/anil-exception-response/health.svg)](https://phpackages.com/packages/anil-exception-response)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
