Fr3nch13/CakePHP Utilities

ExceptionTrap
in package
uses EventDispatcherTrait, InstanceConfigTrait

Entry point to CakePHP's exception handling.

Using the register() method you can attach an ExceptionTrap to PHP's default exception handler and register a shutdown handler to handle fatal errors.

When exceptions are trapped the Exception.beforeRender event is triggered. Then exceptions are logged (if enabled) and finally 'rendered' using the defined renderer.

Stopping the Exception.beforeRender event has no effect, as we always need to render a response to an exception and custom renderers should be used if you want to replace or skip rendering an exception.

If undefined, an ExceptionRenderer will be selected based on the current SAPI (CLI or Web).

Table of Contents

Properties

$_config  : array<string, mixed>
Runtime config
$_configInitialized  : bool
Whether the config property has already been configured with defaults
$_defaultConfig  : array<string, mixed>
Configuration options. Generally these will be defined in your config/app.php
$_eventClass  : string
Default class name for new event objects.
$_eventManager  : EventManagerInterface|null
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
$callbacks  : array<string|int, Closure>
A list of handling callbacks.
$disabled  : bool
Track if this trap was removed from the global handler.
$registeredTrap  : ExceptionTrap|null
The currently registered global exception handler

Methods

__construct()  : mixed
Constructor
configShallow()  : $this
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
dispatchEvent()  : EventInterface
Wrapper for creating and dispatching events.
getConfig()  : mixed
Returns the config.
getConfigOrFail()  : mixed
Returns the config for this specific key.
getEventManager()  : EventManagerInterface
Returns the Cake\Event\EventManager manager instance for this object.
handleException()  : void
Handle uncaught exceptions.
handleFatalError()  : void
Display/Log a fatal error.
handleShutdown()  : void
Shutdown handler
increaseMemoryLimit()  : void
Increases the PHP "memory_limit" ini setting by the specified amount in kilobytes
instance()  : ExceptionTrap|null
Get the registered global instance if set.
logException()  : void
Log an exception.
logger()  : ErrorLoggerInterface
Get an instance of the logger.
logInternalError()  : void
Trigger an error that occurred during rendering an exception.
register()  : void
Attach this ExceptionTrap to PHP's default exception handler.
renderer()  : ExceptionRendererInterface
Get an instance of the renderer.
setConfig()  : $this
Sets the config.
setEventManager()  : $this
Returns the Cake\Event\EventManagerInterface instance for this object.
unregister()  : void
Remove this instance from the singleton
_configDelete()  : void
Deletes a single config key.
_configRead()  : mixed
Reads a config key.
_configWrite()  : void
Writes a config key.
chooseRenderer()  : ExceptionRendererInterface>
Choose an exception renderer based on config or the SAPI

Properties

$_configInitialized

Whether the config property has already been configured with defaults

protected bool $_configInitialized = false

$_defaultConfig

Configuration options. Generally these will be defined in your config/app.php

protected array<string, mixed> $_defaultConfig = ['exceptionRenderer' => null, 'logger' => \Cake\Error\ErrorLogger::class, 'stderr' => null, 'log' => true, 'skipLog' => [], 'trace' => false, 'extraFatalErrorMemory' => 4]
  • exceptionRenderer - string - The class responsible for rendering uncaught exceptions. The chosen class will be used for for both CLI and web environments. If you want different classes used in CLI and web environments you'll need to write that conditional logic as well. The conventional location for custom renderers is in src/Error. Your exception renderer needs to implement the render() method and return either a string or Http\Response.
  • log Set to false to disable logging.
  • logger - string - The class name of the error logger to use.
  • trace - boolean - Whether or not backtraces should be included in logged exceptions.
  • skipLog - array - List of exceptions to skip for logging. Exceptions that extend one of the listed exceptions will also not be logged. E.g.:
    'skipLog' => ['Cake\Http\Exception\NotFoundException', 'Cake\Http\Exception\UnauthorizedException']
    
    This option is forwarded to the configured logger
  • extraFatalErrorMemory - int - The number of megabytes to increase the memory limit by when a fatal error is encountered. This allows breathing room to complete logging or error handling.
  • stderr Used in console environments so that renderers have access to the current console output stream.

$_eventClass

Default class name for new event objects.

protected string $_eventClass = \Cake\Event\Event::class

$callbacks

A list of handling callbacks.

protected array<string|int, Closure> $callbacks = []

Callbacks are invoked for each error that is handled. Callbacks are invoked in the order they are attached.

$disabled

Track if this trap was removed from the global handler.

protected bool $disabled = false

$registeredTrap

The currently registered global exception handler

protected static ExceptionTrap|null $registeredTrap = null

This is best effort as we can't know if/when another exception handler is registered.

Methods

__construct()

Constructor

public __construct([array<string, mixed> $options = [] ]) : mixed
Parameters
$options : array<string, mixed> = []

An options array. See $_defaultConfig.

configShallow()

Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.

public configShallow(array<string, mixed>|string $key[, mixed|null $value = null ]) : $this

Setting a specific value:

$this->configShallow('key', $value);

Setting a nested value:

$this->configShallow('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->configShallow(['one' => 'value', 'another' => 'value']);
Parameters
$key : array<string, mixed>|string

The key to set, or a complete array of configs.

$value : mixed|null = null

The value to set.

Return values
$this

dispatchEvent()

Wrapper for creating and dispatching events.

public dispatchEvent(string $name[, array<string|int, mixed>|null $data = null ][, object|null $subject = null ]) : EventInterface

Returns a dispatched event.

Parameters
$name : string

Name of the event.

$data : array<string|int, mixed>|null = null

Any value you wish to be transported with this event to it can be read by listeners.

$subject : object|null = null

The object that this event applies to ($this by default).

Return values
EventInterface

getConfig()

Returns the config.

public getConfig([string|null $key = null ][, mixed $default = null ]) : mixed

Usage

Reading the whole config:

$this->getConfig();

Reading a specific value:

$this->getConfig('key');

Reading a nested value:

$this->getConfig('some.nested.key');

Reading with default value:

$this->getConfig('some-key', 'default-value');
Parameters
$key : string|null = null

The key to get or null for the whole config.

$default : mixed = null

The return value when the key does not exist.

Return values
mixed

Configuration data at the named key or null if the key does not exist.

getConfigOrFail()

Returns the config for this specific key.

public getConfigOrFail(string $key) : mixed

The config value for this key must exist, it can never be null.

Parameters
$key : string

The key to get.

Tags
throws
InvalidArgumentException
Return values
mixed

Configuration data at the named key

getEventManager()

Returns the Cake\Event\EventManager manager instance for this object.

public getEventManager() : EventManagerInterface

You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.

Return values
EventManagerInterface

handleFatalError()

Display/Log a fatal error.

public handleFatalError(int $code, string $description, string $file, int $line) : void
Parameters
$code : int

Code of error

$description : string

Error description

$file : string

File on which error occurred

$line : int

Line that triggered the error

handleShutdown()

Shutdown handler

public handleShutdown() : void

Convert fatal errors into exceptions that we can render.

increaseMemoryLimit()

Increases the PHP "memory_limit" ini setting by the specified amount in kilobytes

public increaseMemoryLimit(int $additionalKb) : void
Parameters
$additionalKb : int

Number in kilobytes

instance()

Get the registered global instance if set.

public static instance() : ExceptionTrap|null

Keep in mind that the global state contained here is mutable and the object returned by this method could be a stale value.

Return values
ExceptionTrap|null

The global instance or null.

logException()

Log an exception.

public logException(Throwable $exception[, ServerRequestInterface|null $request = null ]) : void

Primarily a public function to ensure consistency between global exception handling and the ErrorHandlerMiddleware. This method will apply the skipLog filter skipping logging if the exception should not be logged.

After logging is attempted the Exception.beforeRender event is triggered.

Parameters
$exception : Throwable

The exception to log

$request : ServerRequestInterface|null = null

The optional request

logInternalError()

Trigger an error that occurred during rendering an exception.

public logInternalError(Throwable $exception) : void

By triggering an E_USER_ERROR we can end up in the default exception handling which will log the rendering failure, and hopefully render an error page.

Parameters
$exception : Throwable

Exception to log

register()

Attach this ExceptionTrap to PHP's default exception handler.

public register() : void

This will replace the existing exception handler, and the previous exception handler will be discarded.

setConfig()

Sets the config.

public setConfig(array<string, mixed>|string $key[, mixed|null $value = null ][, bool $merge = true ]) : $this

Usage

Setting a specific value:

$this->setConfig('key', $value);

Setting a nested value:

$this->setConfig('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->setConfig(['one' => 'value', 'another' => 'value']);
Parameters
$key : array<string, mixed>|string

The key to set, or a complete array of configs.

$value : mixed|null = null

The value to set.

$merge : bool = true

Whether to recursively merge or overwrite existing config, defaults to true.

Tags
throws
CakeException

When trying to set a key that is invalid.

Return values
$this

setEventManager()

Returns the Cake\Event\EventManagerInterface instance for this object.

public setEventManager(EventManagerInterface $eventManager) : $this

You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.

Parameters
$eventManager : EventManagerInterface

the eventManager to set

Return values
$this

unregister()

Remove this instance from the singleton

public unregister() : void

If this instance is not currently the registered singleton nothing happens.

_configDelete()

Deletes a single config key.

protected _configDelete(string $key) : void
Parameters
$key : string

Key to delete.

Tags
throws
CakeException

if attempting to clobber existing config

_configRead()

Reads a config key.

protected _configRead(string|null $key) : mixed
Parameters
$key : string|null

Key to read.

_configWrite()

Writes a config key.

protected _configWrite(array<string, mixed>|string $key, mixed $value[, string|bool $merge = false ]) : void
Parameters
$key : array<string, mixed>|string

Key to write to.

$value : mixed

Value to write.

$merge : string|bool = false

True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.

Tags
throws
CakeException

if attempting to clobber existing config

chooseRenderer()

Choose an exception renderer based on config or the SAPI

protected chooseRenderer() : ExceptionRendererInterface>
Return values
ExceptionRendererInterface>

        
On this page

Search results