Catch an exception while running method (e.g. "Malformed payload") & throw custom exception

This commit is contained in:
Meritoo
2017-09-26 12:49:59 +02:00
parent f5bafdc969
commit 20d7d2f50d
4 changed files with 156 additions and 3 deletions

View File

@@ -0,0 +1,45 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Exception;
use Exception;
use Meritoo\Common\Utilities\Arrays;
/**
* An exception used when an error occurred while running method
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class InvalidResultOfMethodRunException extends Exception
{
/**
* Class constructor
*
* @param Exception $previousException The previous exception, source of an error
* @param string $methodName Name of called method
* @param array $methodArguments (optional) Arguments of the called method
*/
public function __construct(Exception $previousException, $methodName, array $methodArguments = [])
{
$template = "Oops, an error occurred while running method. Is there everything ok? Details:\n"
. "- error: %s,\n"
. "- method: %s,\n"
. '- arguments: %s.';
if (empty($methodArguments)) {
$methodArguments = '(no arguments)';
} else {
$methodArguments = Arrays::valuesKeys2string($methodArguments, ', ', '=', '"');
}
$message = sprintf($template, $previousException->getMessage(), $methodName, $methodArguments);
parent::__construct($message, $previousException->getCode());
}
}

View File

@@ -3,7 +3,9 @@
namespace Meritoo\LimeSurvey\ApiClient\Manager;
use JsonRPC\Client as RpcClient;
use JsonRPC\Exception\InvalidJsonFormatException;
use Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration;
use Meritoo\LimeSurvey\ApiClient\Exception\InvalidResultOfMethodRunException;
use Meritoo\LimeSurvey\ApiClient\Exception\UnknownMethodException;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
@@ -47,14 +49,22 @@ class JsonRpcClientManager
* @return mixed
*
* @throws UnknownMethodException
* @throws InvalidResultOfMethodRunException
*/
public function runMethod($method, $arguments = [])
{
$result = null;
$method = MethodType::getValidatedMethod($method);
return $this
->getRpcClient()
->execute($method, $arguments);
try {
$result = $this
->getRpcClient()
->execute($method, $arguments);
} catch (InvalidJsonFormatException $exception) {
throw new InvalidResultOfMethodRunException($exception, $method);
}
return $result;
}
/**