PHPackages                             mixerapi/exception-render - 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. [Validation &amp; Sanitization](/categories/validation)
4. /
5. mixerapi/exception-render

ActiveCakephp-plugin[Validation &amp; Sanitization](/categories/validation)

mixerapi/exception-render
=========================

Handles rendering entity validation errors and other exceptions for your API

v2.0.8(1mo ago)184.5k↑13.6%11MITPHPPHP ^8.1

Since Sep 27Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/mixerapi/exception-render)[ Packagist](https://packagist.org/packages/mixerapi/exception-render)[ RSS](/packages/mixerapi-exception-render/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependencies (15)Versions (33)Used By (1)

MixerAPI ExceptionRender
========================

[](#mixerapi-exceptionrender)

[![Latest Version on Packagist](https://camo.githubusercontent.com/3b956c56d3698287bb82cc7df83de1a12a0c9c2a82871dd14e50aa79b6d90b4f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d697865726170692f657863657074696f6e2d72656e6465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mixerapi/exception-render)[![Build](https://github.com/mixerapi/mixerapi-dev/workflows/Build/badge.svg?branch=master)](https://github.com/mixerapi/mixerapi-dev/actions?query=workflow%3ABuild)[![Coverage Status](https://camo.githubusercontent.com/980eb71f87b8f84d118d946d1a90203dbc53bbc8ac87363bc543899b32c0d2a0/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6d697865726170692f6d697865726170692d6465762f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/mixerapi/mixerapi-dev?branch=master)[![MixerApi](https://camo.githubusercontent.com/bca1ea90642661e0908fc7ad1c1cdbd704cda1063a2cb40801fab9d0ccdbd6af/68747470733a2f2f6d697865726170692e636f6d2f6173736574732f696d672f6d697865722d6170692d7265642e737667)](http://mixerapi.com)[![CakePHP](https://camo.githubusercontent.com/21b7bf61684c39eabf40bb424dd733f6f3a4bd11de430f8accc24ba0445b4b9b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f63616b657068702d253545342e322d7265643f6c6f676f3d63616b65706870)](https://book.cakephp.org/4/en/index.html)[![Minimum PHP Version](https://camo.githubusercontent.com/7f2179949cf3def20f5d08c400d94cf1c6c68c30bdaa05546c78e33eccded56f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e302d3838393242462e7376673f6c6f676f3d706870)](https://php.net/)

This plugin handles rendering entity validation errors and other exceptions for your API.

- Integrates with [Validator](https://book.cakephp.org/4/en/core-libraries/validation.html) on `add()` and `edit()`actions.
- Adds the short name of the Exception thrown to the response

Read more at [MixerAPI.com](https://mixerapi.com).

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

[](#installation)

!!! tip "" You can skip this step if you have MixerApi installed.

```
composer require mixerapi/exception-render
bin/cake plugin load MixerApi/ExceptionRender
```

Alternatively after composer installing you can manually load the plugin in your Application:

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

Setup
-----

[](#setup)

In your `config/app.php` file change the default `exceptionRenderer`:

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

Usage
-----

[](#usage)

Define your Validations as normal in your Table classes and `MixerApiExceptionRenderer` handles the rest by attaching a listener to the [afterMarshall](https://book.cakephp.org/4/en/orm/table-objects.html#aftermarshal) event which fires when request data is merged into entities during patchEntity() or newEntity() calls. If a validation fails then a `ValidationException` is thrown and rendered with an HTTP 422 status code.

Example controller action:

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

Output:

```
{
  "exception": "ValidationException",
  "message": "Error saving resource `Actor`",
  "url": "/actors",
  "code": 422,
  "violations": [
    {
      "propertyPath": "first_name",
      "messages": [
        {
          "rule": "_required",
          "message": "This field is required"
        }
      ]
    },
    {
      "propertyPath": "last_name",
      "messages": [
        {
          "rule": "_required",
          "message": "This field is required"
        }
      ]
    }
  ]
}
```

Using the controller example from above, we can catch the exception if desired and perform additional logic:

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

### Exceptions

[](#exceptions)

For non-validation based exceptions, even your projects own custom exceptions, the output is similar to CakePHP native output with the addition of an exception attribute. For example, a `MethodNotAllowedException` would result in:

```
{
  "exception": "MethodNotAllowedException",
  "message": "Your exception message here",
  "url": "/actors",
  "code": 405
}
```

If for instance you have a custom exception that is thrown, such as `InventoryExceededException`, you would see:

```
{
  "exception": "InventoryExceededException",
  "message": "No inventory exists",
  "url": "/requested-url",
  "code": 500
}
```

Providing an Exception name, in conjunction with the status code already provided by CakePHP, enables API clients to tailor their exception handling.

### Disabling ValidationExceptions

[](#disabling-validationexceptions)

There may be times when you don't want ValidationExceptions to run. You can easily disable the event:

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

Another example is you may only want the event to run for non-CLI portions of your application:

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

### Changing Error Messages

[](#changing-error-messages)

ExceptionRender dispatches a `MixerApi.ExceptionRender.beforeRender` event that you can listen for to alter `viewVars`and `serialize` variables. Both are accessible via the `MixerApi\ExceptionRender\ErrorDecorator`.

Example:

```
