PHP code example of ufo-tech / rpc-exceptions

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

    

ufo-tech / rpc-exceptions example snippets


use Ufo\RpcError\AbstractRpcErrorException;

$error = AbstractRpcErrorException::fromCode(-32700);
$error = AbstractRpcErrorException::fromArray(['code' => -32600, 'message' => 'Invalid request']);
$error = AbstractRpcErrorException::fromJson('{"code":-32500,"message":"Upstream failed"}');
$error = AbstractRpcErrorException::fromThrowable(new \RuntimeException('Failed', 500));

use Ufo\RpcError\CustomApplicationException;

throw new CustomApplicationException('Limit reached', 4010);

use Ufo\RpcError\AbstractRpcErrorException;
use Ufo\RpcError\IProcedureExceptionInterface;

class UnsupportedProviderException extends AbstractRpcErrorException implements IProcedureExceptionInterface
{
    protected $code = -31050;
    protected $message = 'Unsupported provider';
}

class MyRpcError extends AbstractRpcErrorException
{
    const array ERROR_MAPPING = [
        -31050 => UnsupportedProviderException::class,
    ] + parent::ERROR_MAPPING;
}

MyRpcError::fromCode(-31050); // UnsupportedProviderException

throw (new RpcBadParamException('Invalid input'))
    ->pushToExtraData(['field' => 'email', 'attempt' => 3]);

$restored = AbstractRpcErrorException::fromJson($errorObjectFromTheWire);
$restored->getExtraData(); // ['field' => 'email', 'attempt' => 3]

use Ufo\RpcError\ExceptionToArrayTransformer;

$data = (new ExceptionToArrayTransformer($error, 'prod'))->infoByEnvironment();

throw new ConstraintsImposedException('Invalid payload', ['email' => 'NotBlank']);