PHP code example of levacic / exception-with-context

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

    

levacic / exception-with-context example snippets




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,
        ];
    }
}

if (!$user->isActivated()) {
    throw new UserNotActivated($user->id);
}

$logger->error($exception->getMessage(), $exception->getContext());

$response = makeRequestToExternalApi($someRequestData);

if ($response->statusCode !== 200) {
    throw new InvalidResponseFromExternalApi(
        $someRequestData,
        $response->statusCode,
        $response->body,
        $response->headers,
    );
}

return $response;

try {
    $response = $apiService->getResponse();
} catch (InvalidResponseFromExternalApi $exception) {
    $logger->error($exception->getMessage(), $exception->getContext());

    return new \Symfony\Component\HttpFoundation\Response('External API is currently unavailable.', 503);
}

return $response;

protected function exceptionContext(Throwable $e)
{
    if ($e instanceof ExceptionWithContext) {
        return $e->getContext();
    }

    return parent::exceptionContext($e);
}