3 namespace seekat\Exception
;
12 * @code-coverage-ignore
14 class RequestException
extends \Exception
implements Exception
23 * The response of the request which caused the exception
29 * @param Response $response
31 function __construct(Response
$response) {
32 $this->response
= $response;
34 if (($h = $response->getHeader("Content-Type", Header
::class))
35 && $h->match("application/json", Header
::MATCH_WORD
)
36 && $failure = json_decode($response->getBody())) {
37 $message = $failure->message
;
38 if (isset($failure->errors
)) {
39 $this->errors
= (array) $failure->errors
;
42 $message = trim($response->getBody()->toString());
45 if (!strlen($message)) {
46 $message = $response->getTransferInfo("error");
48 if (!strlen($message)) {
49 $message = $response->getResponseStatus();
52 parent
::__construct($message, $response->getResponseCode(), null);
59 function getErrors() : array {
66 function getResponse() : Response
{
67 return $this->response
;
71 * Combine any errors into a single string
72 * @staticvar array $reasons
75 function getErrorsAsString() {
77 "missing" => "The resource %1\$s does not exist\n",
78 "missing_field" => "Missing field %2\$s of resource %1\$s\n",
79 "invalid" => "Invalid formatting of field %2\$s of resource %1\$s\n",
80 "already_exists" => "A resource %1\$s with the same value of field %2\$s already exists\n",
84 return $this->response
;
87 $errors = "JSON errors:\n";
88 foreach ($this->errors
as $error) {
89 if ($error->code
=== "custom") {
90 $errors .= $error->message
. "\n";
92 $errors .= sprintf($reasons[$error->code
], $error->resource, $error->field
);
101 function __toString() : string {
102 return parent
::__toString() . "\n". $this->getErrorsAsString();