【问题标题】:zf2 JSON-RPC server how to return custom errorzf2 JSON-RPC 服务器如何返回自定义错误
【发布时间】:2013-08-19 19:01:48
【问题描述】:

我正在寻找从 JSON-RPC 公开类返回自定义错误的正确方法。

JSON-RPC 具有用于报告错误情况的特殊格式。所有错误都需要至少提供错误消息和错误代码;可选地,它们可以提供额外的数据,例如回溯。

错误代码源自 XML-RPC EPI 项目推荐的代码。 Zend\Json\Server 根据错误情况适当地分配代码。对于应用程序异常,使用代码“-32000”。

我将使用文档中示例代码的除法来解释:

<?php
/**
 * Calculator - sample class to expose via JSON-RPC
 */
class Calculator
{
    /**
     * Return sum of two variables
     *
     * @param  int $x
     * @param  int $y
     * @return int
     */
    public function add($x, $y)
    {
        return $x + $y;
    }

    /**
     * Return difference of two variables
     *
     * @param  int $x
     * @param  int $y
     * @return int
     */
    public function subtract($x, $y)
    {
        return $x - $y;
    }

    /**
     * Return product of two variables
     *
     * @param  int $x
     * @param  int $y
     * @return int
     */
    public function multiply($x, $y)
    {
        return $x * $y;
    }

    /**
     * Return the division of two variables
     *
     * @param  int $x
     * @param  int $y
     * @return float
     */
    public function divide($x, $y)
    {
        if ($y == 0) {
            // Say "y must not be zero" in proper JSON-RPC error format
            // e.g. something like {"error":{"code":-32600,"message":"Invalid Request","data":null},"id":null} 
        } else {
            return $x / $y;
        }
    }
}


$server = new Zend\Json\Server\Server();
$server->setClass('Calculator');

if ('GET' == $_SERVER['REQUEST_METHOD']) {
    // Indicate the URL endpoint, and the JSON-RPC version used:
    $server->setTarget('/json-rpc.php')
    ->setEnvelope(Zend\Json\Server\Smd::ENV_JSONRPC_2);

    // Grab the SMD
    $smd = $server->getServiceMap();

    // Return the SMD to the client
    header('Content-Type: application/json');
    echo $smd;
    return;
}

$server->handle();

附言是的,我尝试过 Google 搜索。

【问题讨论】:

    标签: zend-framework2 json-rpc


    【解决方案1】:

    免责声明:我没有使用 Zend\Json\Server 的经验 :)

    如果您谈论错误响应,我可以将其与Server::fault() 方法(也称为available on Github)相关联。所以我假设如果 fault() 被调用并注入到响应中,它将根据您推荐的 XML-RPC 服务器标准返回带有错误消息的响应。

    处理程序方法将实际工作代理到_handle()(链接到源),其中try/catch 将调度封装到(在您的情况下)Calculator 类。

    根据异常消息和异常代码调用故障。因此,我认为它只是抛出一个异常并在那里设置正确的消息/代码:

    use Zend\Json\Server\Error;
    
    class Calculator
    {
        public function divide($x, $y) 
        {
            if (0 === $y) {
                throw new InvalidArgumentException(
                    'Denominator must be a non-zero numerical',
                    Error::ERROR_INVALID_PARAMS
                );
            }
    
            // Rest here
        }
    
        // Rest here
    }
    

    PS。我这里也改了你的错误码,对我来说感觉-32602(invalid params)比-32600(invalid request)更合适。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      • 1970-01-01
      • 2014-04-20
      相关资源
      最近更新 更多