PHP code example of beter / exception-with-context
1. Go to this page and download the library: Download beter/exception-with-context 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/ */
beter / exception-with-context example snippets
use Beter\ExceptionWithContext\ExceptionWithContext;
$exceptionCode = 0;
$previousException = null;
$context = [
'userIp' => '1.2.3.4',
'userId' => 1,
'request' => [
'headers' => [ /* put headers data, for example */ ]
],
];
$e = new ExceptionWithContext('Action is not allowed for the user', $exceptionCode, $previousException, $context);
// or you may not to pass the context
$e = new ExceptionWithContext('Action is not allowed for the user', $exceptionCode, $previousException);
// or even skip $exceptionCode and $previousException
$e = new ExceptionWithContext('Action is not allowed for the user');
// or set context via setContext method call
$e = new ExceptionWithContext('Action is not allowed for the user');
$e->setContext($context);
// and get context back
var_dump($e->getContext());
use Beter\ExceptionWithContext\ExceptionWithContext;
try {
do_smth();
} catch (\Throwable $catched) {
$e = new ExceptionWithContext('Something went wrong', 0, $catched, ['key' => 'value']);
}
use Beter\ExceptionWithContext\ExceptionWithContextInterface;
use Beter\ExceptionWithContext\ExceptionWithContextTrait;
class CustomException extends \Exception implements ExceptionWithContextInterface
{
use ExceptionWithContextTrait;
public function __construct($message = "", $code = 0, Throwable $previous = null, array $context = [])
{
$this->context = $context;
parent::__construct($message, $code, $previous);
}
}
$e = new CustomException('Message text', 0, null, ['key' => 'value']);
$e->setContext(['newkey' => 'newvalue']);
var_dump($e->getContext());
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.