1: <?php
2: /**
3: * This file is part of the Pipeliner API client library for PHP
4: *
5: * Copyright 2014 Pipelinersales, Inc. All Rights Reserved.
6: * For the full license information, see the attached LICENSE file.
7: */
8:
9: namespace PipelinerSales\ApiClient\Http;
10:
11: use PipelinerSales\ApiClient\PipelinerClientException;
12:
13: /**
14: * Exception related to HTTP requests.
15: */
16: class PipelinerHttpException extends PipelinerClientException
17: {
18:
19: /** @var Response $response */
20: private $response;
21: private $jsonError = array();
22:
23: public function __construct($response, $message, $httpError = '', $code = 0, $previous = null)
24: {
25: parent::__construct($message, $code, $previous);
26: $this->response = $response;
27:
28: if (!empty($httpError)) {
29: $this->message .= 'HTTP error: [' . $httpError . ']';
30: }
31:
32: $body = $this->response->getBody();
33: if (!empty($body)) {
34: $this->jsonError = json_decode($body, true);
35: if (!empty($this->jsonError)) {
36: $this->message .= 'Response error: [' . $this->getErrorCode() . ': ' . $this->getErrorMessage() . ']';
37: }
38: }
39:
40: $this->message .= ', HTTP code ' . $this->response->getStatusCode();
41: }
42:
43: /**
44: * @return Response
45: */
46: public function getHttpResponse()
47: {
48: return $this->response;
49: }
50:
51: /**
52: * The error code specified in the API, or 0 if the error response is not available.
53: * @return integer
54: */
55: public function getErrorCode()
56: {
57: if (isset($this->jsonError['errorcode'])) {
58: return intval($this->jsonError['errorcode']);
59: }
60: return 0;
61: }
62:
63: /**
64: * The error message specified in the API, or an empty string if not available.
65: * @return string
66: */
67: public function getErrorMessage()
68: {
69: if (is_string($this->jsonError)) {
70: return $this->jsonError;
71: } elseif (isset($this->jsonError['message'])) {
72: return $this->jsonError['message'];
73: }
74: return '';
75: }
76: }
77: