diff --git a/src/Errors/BadRequestError.php b/src/Errors/BadRequestError.php index e017e33..3f6a0cb 100644 --- a/src/Errors/BadRequestError.php +++ b/src/Errors/BadRequestError.php @@ -6,9 +6,9 @@ class BadRequestError extends Error { protected $field = null; - public function __construct($message, $code, $httpStatusCode, $field = null) + public function __construct($message, $code, $httpStatusCode, $field = null, array $context = []) { - parent::__construct($message, $code, $httpStatusCode); + parent::__construct($message, $code, $httpStatusCode, $context); $this->field = $field; } @@ -17,4 +17,4 @@ public function getField() { return $this->field; } -} \ No newline at end of file +} diff --git a/src/Errors/Error.php b/src/Errors/Error.php index eeaae7d..eb01fdc 100644 --- a/src/Errors/Error.php +++ b/src/Errors/Error.php @@ -7,18 +7,41 @@ class Error extends Exception { protected $httpStatusCode; + protected $context = []; - public function __construct($message, $code, $httpStatusCode) + public function __construct($message, $code, $httpStatusCode, array $context = []) { - $this->code = $code; - - $this->message = $message; + parent::__construct($message); + $this->code = $code; $this->httpStatusCode = $httpStatusCode; + $this->context = $context; } public function getHttpStatusCode() { return $this->httpStatusCode; } -} \ No newline at end of file + + public function getSource() + { + return $this->context['source'] ?? null; + } + + public function getStep() + { + return $this->context['step'] ?? null; + } + + public function getReason() + { + return $this->context['reason'] ?? null; + } + + public function getMetadata() + { + $metadata = $this->context['metadata'] ?? null; + + return is_array($metadata) ? $metadata : null; + } +} diff --git a/src/Request.php b/src/Request.php index 7227410..2b12d48 100644 --- a/src/Request.php +++ b/src/Request.php @@ -164,18 +164,22 @@ protected function processError($body, $httpStatusCode, $response) // This is the fully qualified error class name $error = __NAMESPACE__.'\Errors\\' . $error; - $description = $body['error']['description']; + $err = $body['error']; + $description = $err['description'] ?? ''; - $field = null; - if (isset($body['error']['field'])) - { - $field = $body['error']['field']; + $context = [ + 'source' => $err['source'] ?? null, + 'step' => $err['step'] ?? null, + 'reason' => $err['reason'] ?? null, + 'metadata' => isset($err['metadata']) && is_array($err['metadata']) ? $err['metadata'] : null, + ]; - // Create an instance of the error and then throw it - throw new $error($description, $code, $httpStatusCode, $field); + if ($error === __NAMESPACE__.'\Errors\BadRequestError') + { + throw new $error($description, $code, $httpStatusCode, $err['field'] ?? null, $context); } - throw new $error($description, $code, $httpStatusCode); + throw new $error($description, $code, $httpStatusCode, $context); } protected function throwServerError($body, $httpStatusCode)