Giter Site home page Giter Site logo

json-exception-handler's Introduction

Laravel Json Exception Handler

StyleCI Scrutinizer Code Quality

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

JsonAPI

Using JsonAPI standard to responses!

Features

Default error response:

{
    "errors": [
        {
            "status": 404,
            "code": 15,
            "source": {
                "pointer": ""
            },
            "title": "Route not found.",
            "detail": "NotFoundHttpException line 179 in RouteCollection.php"
        }
    ]
}

To Illuminate\Validation\ValidationException:

{
    "errors": [
        {
            "status": 422,
            "code": 1411,
            "source": {
                "parameter": "name"
            },
            "title": "Required validation failed on field name",
            "detail": "The name field is required."
        },
        {
            "status": 422,
            "code": 1433,
            "source": {
                "parameter": "password"
            },
            "title": "Min validation failed on field password",
            "detail": "The password must be at least 6 characters."
        },
        {
            "status": 422,
            "code": 1432,
            "source": {
                "parameter": "password"
            },
            "title": "Confirmed validation failed on field password",
            "detail": "The password confirmation does not match."
        }
    ]
}

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
  • GuzzleHttp\Exception\ClientException
  • Cielo\API30\Ecommerce\Request\CieloRequestException

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

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

class UserController extends Controller
{
    ...

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

        // 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);
    }

Response References:

json-exception-handler's People

Contributors

sfelix-martins avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.