-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathJsonRpcError.php
97 lines (82 loc) · 2.64 KB
/
JsonRpcError.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace georgique\yii2\jsonrpc;
use georgique\yii2\jsonrpc\exceptions\JsonRpcException;
use yii\base\UserException;
use yii\helpers\ArrayHelper;
/**
* Class JsonRpcError
* @property int $code
* @property string $message
* @property array $data
* @package georgique\yii2\jsonrpc
*/
class JsonRpcError implements \JsonSerializable
{
public $code;
public $message;
public $data;
/**
* JsonRpcError constructor.
* @param \Exception $exception
*/
public function __construct(\Throwable $exception)
{
$this->code = $exception->getCode();
$this->message = $this->getExceptionMessage($exception);
$this->data = [];
if ($exception instanceof JsonRpcException && !empty($exception->getData())) {
$this->data = $exception->getData();
}
if (defined('YII_DEBUG') && YII_DEBUG) {
$this->data['exception'] = $this->convertExceptionToArray($exception);
}
// We need to provide client with an original error message
$this->data['human_message'] = ($exception->getPrevious()) ? $exception->getPrevious()->getMessage() : $exception->getMessage();
$this->data['error_code'] = ($exception->getPrevious()) ? $exception->getPrevious()->getCode() : null;
}
/**
* @return array|mixed
*/
public function jsonSerialize()
{
$fields = ArrayHelper::toArray($this);
if (!isset($this->data)) {
unset($fields['data']);
}
return $fields;
}
/**
* @param \Exception $exception
* @return string
*/
protected function getExceptionMessage(\Throwable $exception)
{
$message = $exception->getMessage();
return !empty($message) ?
$message :
(method_exists($exception, 'getName') ? $exception->getName() : '');
}
/**
* @param \Exception $exception
* @return array
*/
protected function convertExceptionToArray(\Throwable $exception)
{
$errorArray = [];
$errorArray['type'] = get_class($exception);
if (!$exception instanceof UserException) {
$errorArray += [
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'stack-trace' => explode("\n", $exception->getTraceAsString())
];
if ($exception instanceof \yii\db\Exception) {
$errorArray['error-info'] = $exception->errorInfo;
}
}
if (($prev = $exception->getPrevious()) !== null) {
$errorArray['previous'] = new JsonRpcError($prev);
}
return $errorArray;
}
}