PHPackages                             sfelix-martins/json-exception-handler - 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. [API Development](/categories/api)
4. /
5. sfelix-martins/json-exception-handler

ActiveLibrary[API Development](/categories/api)

sfelix-martins/json-exception-handler
=====================================

Adds more power to Laravel Exceptions Handler to treat json responses

v2.3.0(5y ago)1764.6k↓61.3%15[2 PRs](https://github.com/sfelix-martins/json-exception-handler/pulls)MITPHPPHP &gt;=7.0.0CI failing

Since Aug 27Pushed 4y agoCompare

[ Source](https://github.com/sfelix-martins/json-exception-handler)[ Packagist](https://packagist.org/packages/sfelix-martins/json-exception-handler)[ RSS](/packages/sfelix-martins-json-exception-handler/feed)WikiDiscussions 2.0 Synced 1mo ago

READMEChangelog (8)Dependencies (2)Versions (30)Used By (0)

Laravel Json Exception Handler
==============================

[](#laravel-json-exception-handler)

[![StyleCI](https://camo.githubusercontent.com/4f736432b61aeb677b755c2f019316f866fbb02956fe7015d2942c0750a4d9d8/68747470733a2f2f7374796c6563692e696f2f7265706f732f3130313532393635332f736869656c643f7374796c653d706c6173746963266272616e63683d322e30)](https://styleci.io/repos/101529653?style=plastic&branch=2.0)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/128d4d36622184ad18c3cc358f0b720f560216ec93337297d5955770e5d599e8/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7366656c69782d6d617274696e732f6a736f6e2d657863657074696f6e2d68616e646c65722f6261646765732f7175616c6974792d73636f72652e706e673f623d322e30)](https://scrutinizer-ci.com/g/sfelix-martins/json-exception-handler/?branch=2.0)[![Build Status](https://camo.githubusercontent.com/2277620c5f44d9e5a7d5cc9f5605e94ed66d343c8b198402c41e05166d48fc9f/68747470733a2f2f7472617669732d63692e6f72672f7366656c69782d6d617274696e732f6a736f6e2d657863657074696f6e2d68616e646c65722e7376673f6272616e63683d322e30)](https://travis-ci.org/sfelix-martins/json-exception-handler)

Adds methods to your `App\Exceptions\Handler` to treat json responses. It is most useful if you are building APIs!

Requirements
------------

[](#requirements)

- Laravel Framework &gt;= 5.4
- php &gt;= 7.0

JsonAPI
-------

[](#jsonapi)

Using [JsonAPI](http://jsonapi.org) standard to responses!

Features
--------

[](#features)

Default error response:

```
{
  "errors": [
    {
      "status": "404",
      "code": "13",
      "title": "model_not_found_exception",
      "detail": "User not found",
      "source": {
        "pointer": "data/id"
      }
    }
  ]
}
```

To `Illuminate\Validation\ValidationException`:

```
{
  "errors": [
    {
      "status": "422",
      "code": "1411",
      "title": "Required validation failed on field name",
      "detail": "The name field is required.",
      "source": {
        "pointer": "name"
      }
    },
    {
      "status": "422",
      "code": "1421",
      "title": "Email validation failed on field email",
      "detail": "The email must be a valid email address.",
      "source": {
        "pointer": "email"
      }
    }
  ]
}
```

### Treated Exceptions

[](#treated-exceptions)

- `Illuminate\Auth\Access\AuthorizationException`
- `Illuminate\Auth\AuthenticationException`
- `Illuminate\Database\Eloquent\ModelNotFoundException`
- `Illuminate\Validation\ValidationException`
- `Laravel\Passport\Exceptions\MissingScopeException`
- `League\OAuth2\Server\Exception\OAuthServerException`
- `Symfony\Component\HttpKernel\Exception\NotFoundHttpException`
- `Symfony\Component\HttpKernel\Exception\BadRequestHttpException`

Installing and configuring
--------------------------

[](#installing-and-configuring)

Install the package

```
$ composer require sfelix-martins/json-exception-handler
```

If you are not using **Laravel 5.5** version add the `JsonHandlerServiceProvider` to your `config/app.php` providers array:

```
    'providers' => [
        ...
        SMartins\Exceptions\JsonHandlerServiceProvider::class,
    ],
```

Publish the config to set your own exception codes

```
$ php artisan vendor:publish --provider="SMartins\JsonHandler\JsonHandlerServiceProvider"
```

Set your exception codes on `config/json-exception-handler.php` on codes array.

You can add more fields and codes to `validation_fields` array.

You can add too your models on lang packages to return the Not Found response translated correctly.

In `resources/lang/vendor/exception/lang/$locale` in `exceptions` file you can set on `models` array. Example:

```
    'models' => [
        'User' => 'Usuário',
        'Article' => 'Artigo',
    ]
```

Using
-----

[](#using)

Use the trait on your `App\Exception\Handler` and add method `jsonResponse()`passing the `$exception` if `$request` expects a json response on `render()`method

```
use SMartins\Exceptions\JsonHandler;

class Handler extends ExceptionHandler
{
    use JsonHandler;

    // ...

    public function render($request, Exception $exception)
    {
        if ($request->expectsJson()) {
            return $this->jsonResponse($exception);
        }

        return parent::render($request, $exception);
    }

    // ...
```

### Use sample

[](#use-sample)

```
class UserController extends Controller
{
    // ...

    public function store(Request $request)
    {
        // Validation
        $request->validate($this->rules);

        // or
        $this->validate($request, $this->rules);

        //and or
        Validator::make($request->all(), $this->rules)->validate();

        if (condition()) {
            // Generate response with http code and message
            abort(403, 'Action forbidden!');
        }

        if (anotherCondition()) {
            // Generate response with message and code
            throw new TokenMismatchException("Error Processing Request", 10);
        }
    }

    public function show($id)
    {
        // If not found the default response is called
        $user = User::findOrFail($id);

        // Gate define on AuthServiceProvider
        // Generate an AuthorizationException if fail
        $this->authorize('users.view', $user->id);
    }
```

Extending
---------

[](#extending)

You can too create your own handler to any Exception. E.g.:

- Create a Handler class that extends of `AbstractHandler`:

```
namespace App\Exceptions;

use GuzzleHttp\Exception\ClientException;
use SMartins\Exceptions\Handlers\AbstractHandler;

class GuzzleClientHandler extends AbstractHandler
{
    /**
     * Create instance using the Exception to be handled.
     *
     * @param \GuzzleHttp\Exception\ClientException $e
     */
    public function __construct(ClientException $e)
    {
        parent::__construct($e);
    }
}
```

- You must implements the method `handle()` from `AbstractHandler` class. The method must return an instance of `Error` or `ErrorCollection`:

```
namespace App\Exceptions;

use SMartins\Exceptions\JsonAPI\Error;
use SMartins\Exceptions\JsonAPI\Source;
use GuzzleHttp\Exception\ClientException;
use SMartins\Exceptions\Handlers\AbstractHandler;

class GuzzleClientHandler extends AbstractHandler
{
    // ...

    public function handle()
    {
        return (new Error)->setStatus($this->getStatusCode())
            ->setCode($this->getCode())
            ->setSource((new Source())->setPointer($this->getDefaultPointer()))
            ->setTitle($this->getDefaultTitle())
            ->setDetail($this->exception->getMessage());
    }

    public function getCode()
    {
        // You can add a new type of code on `config/json-exception-handlers.php`
        return config('json-exception-handler.codes.client.default');
    }
}
```

```
namespace App\Exceptions;

use SMartins\Exceptions\JsonAPI\Error;
use SMartins\Exceptions\JsonAPI\Source;
use SMartins\Exceptions\JsonAPI\ErrorCollection;
use SMartins\Exceptions\Handlers\AbstractHandler;

class MyCustomizedHandler extends AbstractHandler
{
    public function __construct(MyCustomizedException $e)
    {
        parent::__construct($e);
    }

    public function handle()
    {
        $errors = (new ErrorCollection)->setStatusCode(400);

        $exceptions = $this->exception->getExceptions();

        foreach ($exceptions as $exception) {
            $error = (new Error)->setStatus(422)
                ->setSource((new Source())->setPointer($this->getDefaultPointer()))
                ->setTitle($this->getDefaultTitle())
                ->setDetail($exception->getMessage());

            $errors->push($error);
        }

        return $errors;
    }
}
```

- Now just registry your customized handler on `App\Exception\Handler` file on attribute `exceptionHandlers`. E.g:

```
namespace App\Exceptions;

use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use SMartins\Exceptions\JsonHandler;

class Handler extends ExceptionHandler
{
    use JsonHandler;

    protected $exceptionHandlers = [
        // Set on key the exception and on value the handler.
        ClientException::class => GuzzleClientHandler::class,
    ];
```

Response References:
--------------------

[](#response-references)

-

###  Health Score

39

—

LowBetter than 85% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity39

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 92.3% 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 ~38 days

Recently: every ~75 days

Total

28

Last Release

2124d ago

Major Versions

v0.5.1 → v1.0.02017-09-16

v1.8.2 → v2.02019-09-18

PHP version history (2 changes)v0.1PHP &gt;=5.6.4

v2.0PHP &gt;=7.0.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/090bb1ed9dd85b5b6d8c63f1f01eff2b3cc8632975c767bae02fc0b8ff3c2fdd?d=identicon)[sam.martins.dev](/maintainers/sam.martins.dev)

---

Top Contributors

[![sfelix-martins](https://avatars.githubusercontent.com/u/22901624?v=4)](https://github.com/sfelix-martins "sfelix-martins (24 commits)")[![designvoid](https://avatars.githubusercontent.com/u/630948?v=4)](https://github.com/designvoid "designvoid (2 commits)")

---

Tags

jsonapilaravelexceptionsjsonapihandler

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/sfelix-martins-json-exception-handler/health.svg)

```
[![Health](https://phpackages.com/badges/sfelix-martins-json-exception-handler/health.svg)](https://phpackages.com/packages/sfelix-martins-json-exception-handler)
```

###  Alternatives

[cloudcreativity/laravel-json-api

JSON API (jsonapi.org) support for Laravel applications.

7881.1M5](/packages/cloudcreativity-laravel-json-api)[aimeos/aimeos-laravel

Cloud native, API first Laravel eCommerce package with integrated AI for ultra-fast online shops, marketplaces and complex B2B projects

8.6k214.7k3](/packages/aimeos-aimeos-laravel)[nilportugues/laravel5-json-api

Laravel 5 JSON API Transformer Package

31232.4k1](/packages/nilportugues-laravel5-json-api)[nilportugues/jsonapi-bundle

Symfony 2 &amp; 3 JSON API Transformer Package

11446.0k](/packages/nilportugues-jsonapi-bundle)[alsvanzelf/jsonapi

Human-friendly library to implement JSON:API without needing to know the specification.

54150.0k5](/packages/alsvanzelf-jsonapi)[nilportugues/laravel5-json-api-dingo

Laravel5 JSONAPI and Dingo together to build APIs fast

311.5k](/packages/nilportugues-laravel5-json-api-dingo)

PHPackages © 2026

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