1 | <?php |
||
2 | |||
3 | namespace Postpay\Exceptions; |
||
4 | |||
5 | use Postpay\Http\Response; |
||
6 | |||
7 | class RESTfulException extends ApiException |
||
8 | { |
||
9 | /** |
||
10 | * @const string Error key returned. |
||
11 | */ |
||
12 | const ERROR_KEY = 'error'; |
||
13 | |||
14 | /** |
||
15 | * @var string API error code. |
||
16 | */ |
||
17 | protected $errorCode; |
||
18 | |||
19 | /** |
||
20 | * Creates a RESTfulException. |
||
21 | * |
||
22 | * @param Response $response The response that threw the exception. |
||
23 | */ |
||
24 | 5 | public function __construct(Response $response) |
|
25 | { |
||
26 | 5 | $this->response = $response; |
|
27 | 5 | $this->decodedBody = $response->json(); |
|
28 | 5 | $this->errorCode = $this->get('code', 'unknown'); |
|
29 | 5 | parent::__construct($this->get('message', 'Unknown error.')); |
|
30 | 5 | } |
|
31 | |||
32 | /** |
||
33 | * Checks isset and returns that or a default value. |
||
34 | * |
||
35 | * @param string $key |
||
36 | * @param mixed $default |
||
37 | * |
||
38 | * @return mixed |
||
39 | */ |
||
40 | 5 | private function get($key, $default = null) |
|
41 | { |
||
42 | 5 | if (isset($this->decodedBody[self::ERROR_KEY][$key])) { |
|
43 | 1 | return $this->decodedBody[self::ERROR_KEY][$key]; |
|
44 | } |
||
45 | 5 | return $default; |
|
46 | } |
||
47 | |||
48 | /** |
||
49 | * Returns API error code. |
||
50 | * |
||
51 | * @return string |
||
52 | */ |
||
53 | 1 | public function getErrorCode() |
|
54 | { |
||
55 | 1 | return $this->errorCode; |
|
56 | } |
||
57 | } |
||
58 |