zend framework2 - zf2 JSON-RPC server how to return custom error -
i'm looking proper way return custom error json-rpc exposed class.
json-rpc has special format reporting error conditions. errors need provide, minimally, error message , error code; optionally, can provide additional data, such backtrace.
error codes derived recommended xml-rpc epi project. zend\json\server appropriately assigns code based on error condition. application exceptions, code ‘-32000’ used.
i use divide method of sample code documentation explain:
<?php /** * calculator - sample class expose via json-rpc */ class calculator { /** * return sum of 2 variables * * @param int $x * @param int $y * @return int */ public function add($x, $y) { return $x + $y; } /** * return difference of 2 variables * * @param int $x * @param int $y * @return int */ public function subtract($x, $y) { return $x - $y; } /** * return product of 2 variables * * @param int $x * @param int $y * @return int */ public function multiply($x, $y) { return $x * $y; } /** * return division of 2 variables * * @param int $x * @param int $y * @return float */ public function divide($x, $y) { if ($y == 0) { // "y must not zero" in proper json-rpc error format // e.g. {"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 url endpoint, , json-rpc version used: $server->settarget('/json-rpc.php') ->setenvelope(zend\json\server\smd::env_jsonrpc_2); // grab smd $smd = $server->getservicemap(); // return smd client header('content-type: application/json'); echo $smd; return; } $server->handle();
p.s. yes tried google search.
disclaimer: have no experience in using zend\json\server
whatsoever :)
if talk error response, can correlate server::fault()
method (also available on github). assume if fault()
called , injected respones, return response error messages according referred recommended xml-rpc server standard.
the handler method proxies actual work _handle()
(linked source) try/catch encapsuling dispatching (in case) calculator class.
the fault called based on exception message , exception code. such think it's throwing exception , setting right message/code there:
use zend\json\server\error; class calculator { public function divide($x, $y) { if (0 === $y) { throw new invalidargumentexception( 'denominator must non-zero numerical', error::error_invalid_params ); } // rest here } // rest here }
ps. changed error code here, me, feels -32602 (invalid params) more appropriate -32600 (invalid request.
Comments
Post a Comment