PHP code example of mixerapi / exception-render

1. Go to this page and download the library: Download mixerapi/exception-render 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/ */

    

mixerapi / exception-render example snippets


# src/Application.php
public function bootstrap(): void
{
    // other logic...
    $this->addPlugin('MixerApi/ExceptionRender');
}

'Error' => [
    'errorLevel' => E_ALL,
    'exceptionRenderer' => MixerApi\ExceptionRender\MixerApiExceptionRenderer::class,
    'skipLog' => [],
    'log' => true,
    'trace' => true,
],

public function add()
{
    $this->request->allowMethod('post');
    $actor = $this->Actors->newEmptyEntity();
    $actor = $this->Actors->patchEntity($actor, $this->request->getData()); // potential ValidationException here
    if ($this->Actors->save($actor)) {
        $this->viewBuilder()->setOption('serialize', 'actor');
        $this->set('actor', $actor);

        return;
    }
    throw new \Exception("Record failed to save");
}


try {
    $actor = $this->Actors->newEmptyEntity();
    $actor = $this->Actors->patchEntity($actor, $this->request->getData());
} catch (\MixerApi\ExceptionRender\ValidationException $e) {
    // do something here
}

Configure::write('MixerApi.ExceptionRender.entity_validation', false);

Configure::write('MixerApi.ExceptionRender.entity_validation', PHP_SAPI !== 'cli');


declare(strict_types=1);

namespace App\Event;

use Cake\Event\EventListenerInterface;
use MixerApi\ExceptionRender\ErrorDecorator;
use MixerApi\ExceptionRender\MixerApiExceptionRenderer;

class ExceptionRender implements EventListenerInterface
{
    public function implementedEvents(): array
    {
        return [
            'MixerApi.ExceptionRender.beforeRender' => 'beforeRender'
        ];
    }

    /**
     * @param \Cake\Event\Event $event
     */
    public function beforeRender(\Cake\Event\Event $event)
    {
        $errorDecorator = $event->getSubject();
        $data = $event->getData();

        if (!$errorDecorator instanceof ErrorDecorator || !$data['exception'] instanceof MixerApiExceptionRenderer) {
            return;
        }

        if (!$data['exception']->getError() instanceof \Authentication\Authenticator\UnauthenticatedException) {
            return;
        }

        $viewVars = $errorDecorator->getViewVars();
        $viewVars['message'] = 'A custom unauthenticated message';
        $errorDecorator->setViewVars($viewVars);
    }
}