PHP code example of sfelix-martins / json-exception-handler

1. Go to this page and download the library: Download sfelix-martins/json-exception-handler library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sfelix-martins / json-exception-handler example snippets


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

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


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

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


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

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

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,
    ];