|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* User: scaytrase |
|
4
|
|
|
* Created: 2016-02-14 13:32 |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace Bankiru\Api\JsonRpc\Listener; |
|
8
|
|
|
|
|
9
|
|
|
use Bankiru\Api\JsonRpc\Exception\JsonRpcException; |
|
10
|
|
|
use Bankiru\Api\JsonRpc\Exception\JsonRpcExceptionInterface; |
|
11
|
|
|
use Bankiru\Api\JsonRpc\Specification\JsonRpcResponse; |
|
12
|
|
|
use Bankiru\Api\Rpc\Event\GetExceptionResponseEvent; |
|
13
|
|
|
use Bankiru\Api\Rpc\Exception\InvalidMethodParametersException; |
|
14
|
|
|
use Bankiru\Api\Rpc\Routing\Exception\MethodNotFoundException; |
|
15
|
|
|
use ScayTrase\Api\JsonRpc\JsonRpcError; |
|
16
|
|
|
use ScayTrase\Api\JsonRpc\JsonRpcRequestInterface; |
|
17
|
|
|
|
|
18
|
|
|
final class ExceptionHandlerListener |
|
19
|
|
|
{ |
|
20
|
|
|
private $debug = false; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* ExceptionHandlerListener constructor. |
|
24
|
|
|
* |
|
25
|
|
|
* @param bool $debug |
|
26
|
|
|
*/ |
|
27
|
|
|
public function __construct($debug) { $this->debug = (bool)$debug; } |
|
28
|
|
|
|
|
29
|
|
|
|
|
30
|
1 |
|
public function onJsonRpcException(GetExceptionResponseEvent $event) |
|
31
|
|
|
{ |
|
32
|
1 |
|
$request = $event->getRequest(); |
|
33
|
1 |
|
if (!$request instanceof JsonRpcRequestInterface) { |
|
34
|
|
|
return; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
1 |
|
$exception = $event->getException(); |
|
38
|
1 |
|
if ($exception instanceof InvalidMethodParametersException) { |
|
39
|
|
|
$exception = |
|
40
|
|
|
JsonRpcException::create( |
|
41
|
|
|
JsonRpcError::INVALID_PARAMS, |
|
42
|
|
|
$exception->getMessage(), |
|
43
|
|
|
$exception->getTrace()); |
|
44
|
1 |
|
} elseif ($exception instanceof MethodNotFoundException) { |
|
45
|
|
|
$exception = |
|
46
|
|
|
JsonRpcException::create( |
|
47
|
|
|
JsonRpcError::METHOD_NOT_FOUND, |
|
48
|
|
|
$exception->getMessage(), |
|
49
|
|
|
$exception->getTrace()); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
1 |
|
if ($exception instanceof JsonRpcExceptionInterface) { |
|
53
|
|
|
$error = $exception->getJsonRpcError(); |
|
54
|
|
|
if (!$this->debug) { |
|
55
|
|
|
$error = new JsonRpcError($error->getCode(), $error->getMessage()); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
$event->setResponse(new JsonRpcResponse($request->getId(), null, $error)); |
|
59
|
|
|
|
|
60
|
|
|
return; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
1 |
|
$data = $this->debug ? (object)['trace' => $exception->getTrace()] : null; |
|
64
|
|
|
|
|
65
|
|
|
$error = |
|
66
|
1 |
|
new JsonRpcError( |
|
67
|
1 |
|
JsonRpcError::INTERNAL_ERROR, |
|
68
|
1 |
|
$event->getException()->getMessage(), |
|
69
|
|
|
$data |
|
70
|
1 |
|
); |
|
71
|
|
|
|
|
72
|
1 |
|
$jsonResponse = new JsonRpcResponse($request->getId(), null, $error); |
|
73
|
1 |
|
$event->setResponse($jsonResponse); |
|
74
|
1 |
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|