PHP code example of jooservices / exceptions

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

    

jooservices / exceptions example snippets


// runnable
use JOOservices\Exceptions\Contracts\JOOExceptionInterface;

$caught = false;

try {
    throw new class('demo') extends \RuntimeException implements JOOExceptionInterface {};
} catch (JOOExceptionInterface $exception) {
    $caught = $exception instanceof \Throwable;
}

use JOOservices\Exceptions\Base\AbstractJOORuntimeException;

abstract class ClientException extends AbstractJOORuntimeException {}

// runnable
use JOOservices\Exceptions\Base\AbstractContextAwareException;
use JOOservices\Exceptions\Support\ErrorCode;
use JOOservices\Exceptions\Support\ExceptionContext;
use JOOservices\Exceptions\Support\LogLevel;

final class HydrationException extends AbstractContextAwareException
{
    public static function forField(string $path, string $expectedType): self
    {
        return (new self("Hydration failed for field '{$path}'"))
            ->withContext(['path' => $path, 'expectedType' => $expectedType]);
    }

    public function errorCode(): string
    {
        return 'dto.hydration.failed';
    }

    public function logLevel(): string
    {
        return LogLevel::ERROR->value;
    }

    protected function copyWithContext(ExceptionContext $context): static
    {
        return new self($this->getMessage(), $this->getCode(), $this->getPrevious(), $context);
    }
}

$exception = HydrationException::forField('user.email', 'string');

// getContext() is always redacted before it reaches the logger
$context = $exception->getContext();
$logPayload = $exception->toLogArray();

// runnable
use JOOservices\Exceptions\Base\AbstractContextAwareException;
use JOOservices\Exceptions\Support\CompositeContextRedactor;

AbstractContextAwareException::setRedactor(
    CompositeContextRedactor::withExtraKeys(['national_id', 'ssn']),
);

AbstractContextAwareException::removeRedactor();