PHP code example of levacic / monolog-exception-with-context-processor

1. Go to this page and download the library: Download levacic/monolog-exception-with-context-processor 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/ */

    

levacic / monolog-exception-with-context-processor example snippets


// Assuming a Monolog\Logger instance:
$monolog->pushProcessor(new ExceptionWithContextProcessor());



declare(strict_types=1);

namespace App\Exceptions;

use Levacic\Exceptions\ExceptionWithContext;
use RuntimeException;
use Throwable;

class UserNotActivated extends RuntimeException implements ExceptionWithContext
{
    /**
     * The ID of the non-activated user.
     */
    private int $userId;

    /**
     * @param int            $userId   The ID of the non-activated user.
     * @param Throwable|null $previous The previous exception.
     * @param int            $code     The internal exception code.
     */
    public function __construct(int $userId, ?Throwable $previous = null, int $code = 0)
    {
        parent::__construct('The user has not been activated yet.', $code, $previous);

        $this->userId = $userId;
    }

    /**
     * @inheritDoc
     */
    public function getContext(): array
    {
        return [
            'userId' => $this->userId,
        ];
    }
}

// Create an exception chain where a RuntimeException wraps an instance of the
// UserNotActivated exception.
$exception = new RuntimeException(
    'An error has occurred',
    0,
    new \App\Exceptions\UserNotActivated(1234),
);

$logger->error(
    $exception->getMessage(),
    [
        'exception' => $exception,
    ],
);